Reading large images as thumbnails locally via HTM

2019-02-03 20:23发布

I am trying to load local images as thumbnails as explained here. My code is below.

This works fine for small images. However, when you try load larger images (e.g. 4mb) there is a huge lag. Is there any way to optimize this?

Thanks

Html

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

Javascript

<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object

// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {

  // Only process image files.
  if (!f.type.match('image.*')) {
    continue;
  }

  var reader = new FileReader();

  // Closure to capture the file information.
  reader.onload = (function(theFile) {
    return function(e) {
      // Render thumbnail.
      var span = document.createElement('span');
      span.innerHTML = ['<img class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/>'].join('');
      document.getElementById('list').insertBefore(span, null);
    };
  })(f);

  // Read in the image file as a data URL.
  reader.readAsDataURL(f);
}
}

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

1条回答
We Are One
2楼-- · 2019-02-03 20:56

There is always a lag when you run something in the main UI thread which involves manipulating non-streaming data in huge blobs. The lag does not come from reading he data, but decoding and displaying the image in the browser UI as this involves synchronous UI operations pushing the large pixel array around in CPU and GPU memory. This is because <img> allocates and moves around memory in the blocks of actual image data size (width * height) which is very large amount for big images and unnecessary detailed to push it up to GPU for just showing it on the screen (causes the lag of several milliseconds).

You can most likely optimize your use case by shrinking the image to displayable size while reading it

However, though the solution described here is near perfect, to implement this one needs to possess advanced Javascript skills and the solution is not going to be legacy compatible (read: Microsoft).

查看更多
登录 后发表回答