6

我正在尝试将本地图像加载为缩略图,如此所述。我的代码如下。

这适用于小图像。但是,当您尝试加载更大的图像(例如 4mb)时,会有很大的延迟。有没有办法优化这个?

谢谢

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>
4

1 回答 1

17

当您在主 UI 线程中运行涉及在巨大 blob 中操作非流式数据的东西时,总会有延迟。延迟不是来自读取数据,而是在浏览器 UI 中解码和显示图像,因为这涉及在 CPU 和 GPU 内存中推动大型像素阵列的同步 UI 操作。这是因为<img>在实际图像数据大小(宽 * 高)的块中分配和移动内存,这对于大图像来说是非常大的量,并且不必要的细节将其推送到 GPU 以仅在屏幕上显示(导致几毫秒)。

您很可能通过在阅读图像时将图像缩小到可显示的大小来优化您的用例

然而,尽管这里描述的解决方案近乎完美,但要实现这一点需要具备高级 Javascript 技能,并且该解决方案不会与旧版兼容(阅读:Microsoft)。

于 2012-12-25T14:54:50.573 回答