Drag and drop images onto a web page and automatically resize them using HTML file APIs

I want to create web pages that allow users to drag and drop images into fields in different parts of the page so that they can print pages with their images.

I want the image to automatically change when it falls into the field. I combined some of the code in http://html5demos.com/file-api with some code in http://html5demos.com/file-api-simple to get something like I want.

In the current version of the code (below), the image width does not change the first time the image is reduced in the field, but this happens a second time.

Any suggestions how can I get the image width to automatically resize the first time the image is deleted in the field?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=620" />
<title>HTML5 Test</title>
</head>
<body>
<header>
      <h1>HTML5 Test 1</h1>
</header>
<style>
   #holder { border: 10px dashed #ccc; width: 300px; height: 300px; margin: 20px auto;}
   #holder.hover { border: 10px dashed #333; }
</style>
<article>
  <div id="holder"></div> 
  <p id="status">File API & FileReader API not supported</p>
  <p>Drag an image from your desktop on to the drop zone above to see the browser read   the contents of the file - without uploading the file to any servers.</p>
</article>
<script>
var holder = document.getElementById('holder'),
    state = document.getElementById('status');

if (typeof window.FileReader === 'undefined') {
  state.className = 'fail';
} else {
  state.className = 'success';
  state.innerHTML = 'File API & FileReader available';
}

holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
  this.className = '';
  e.stopPropagation();
  e.preventDefault();

  var file = e.dataTransfer.files[0],
      reader = new FileReader();
  reader.onload = function (event) {
    var img = new Image();
    img.src = event.target.result;
    // note: no onload required since we've got the dataurl...I think! :)
    if (img.width > 300) { // holder width
      img.width = 300;
  }
  holder.innerHTML = '';
  holder.appendChild(img);
  };
  reader.readAsDataURL(file);

  return false;
};
</script>

</body>
</html>
+3
source share
2 answers

Yeah. Use this source:

http://imgscalr.com/

0
source

I found a simple answer which, it seems to me, works very well for my needs, based on a bit of CSS in http://demos.hacks.mozilla.org/openweb/DnD/dropbox.css used for http: // demos .hacks.mozilla.org / openweb / DnD / .

In the code that I included in my question above, I added this to the CSS code:

   #holder > * {
    display: block;
    margin: auto;
    max-width: 300px;
    max-height: 300px;
}

and I deleted this:

    if (img.width > 300) { // holder width
      img.width = 300;
  }
0
source

All Articles