如何快速预览大图像?

时间:2015-10-21 14:57:30

标签: javascript jquery html html5 file

您好我正在制作一个移动网络应用程序,要求用户将多个图像上传到服务器。一旦他们选择了他们的图像,我想在他们选择上传到服务器之前显示他们图像的缩略图预览。我已经尝试了FileReader方式和createObjectURL(使用画布),并且两种方法都需要很长时间才能显示图像。这通常不会成为问题,但手机上的大多数图像质量都很高,至少为2-3mb。

缩略图生成所需的时间与实际上传图像几乎相同。有什么方法可以在上传之前显示图像的即时低分辨率预览吗?

以下是我用来尝试预览图像的两种方法:

createObjectURL和Canvas方式

<input type="file" id="browseImages" multiple="multiple" accept="image/*">
<output id="list"></output>
document
  .getElementById("browseImages")
  .addEventListener("change", handleFileSelect, true);

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 canvas = document.createElement("canvas");
    canvas.width = 110;
    canvas.height = 100;
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.onload = function() {
      ctx.drawImage(img, 0, 0, 100, 100);
    };
    img.src = window.URL.createObjectURL(f);
    document.getElementById("list").appendChild(canvas);
    window.URL.revokeObjectURL(f);
  }
}

以上方式读取用户选择的图像,并为所选的每个图像创建一个带有图像的画布。

FileReader方式

<input type="file" id="browseImages" multiple="multiple" accept="image/*">
<output id="list"></output>
document
  .getElementById("browseImages")
  .addEventListener("change", handleFileSelect, true);

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 style="height:75px;" 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);
  }
}

上述方法使用FileReader读取然后处理预览图像。

以上两种方法都需要花时间浏览每个图像,读取它然后处理缩略图。它的速度就像我上传图像一样。有什么办法可以生成所选图像的即时缩略图吗?请记住,这是针对移动浏览器的,因此它不会像PC一样拥有大容量内存。

0 个答案:

没有答案