How do I generate a thumbnail client-side in a modern browser?

天涯浪子 提交于 2019-11-27 19:10:07
Daniel Brockman

Here’s what you can do:

function getThumbnail(original, scale) {
  var canvas = document.createElement("canvas");

  canvas.width = original.width * scale;
  canvas.height = original.height * scale;

  canvas.getContext("2d").drawImage(original, 0, 0, canvas.width, canvas.height);

  return canvas
}

Now, to create thumbnails, you simply do the equivalent of this:

var image = document.getElementsByTagName("img")[0];
var thumbnail = getThubmnail(image, 1/5);

document.body.appendChild(thumbnail);

Note: Remember to make sure that the image is loaded (using onload) before trying to make a thumbnail of it.

Okay, the way I can see this working is drawing the image to the canvas at a smaller size, then exporting the canvas. Say you want a 64px thumbnail:

var thumbSize = 64;
var canvas = document.getElementById("canvas");
canvas.width = thumbSize;
canvas.height = thumbSize;
var c = canvas.getContext("2d");
var img = new Image();
img.onload = function(e) {
    c.drawImage(this, 0, 0, thumbSize, thumbSize);
    document.getElementById("thumb").src = canvas.toDataURL("image/png");
};
img.src = fileDataURL;

With this code, an image element with the id "thumb" is used as the thumbnail element. fileDataURL is the data URL that you got from the file API.

More information on drawing images to the canvas: http://diveintohtml5.info/canvas.html#images

And on exporting canvas data: http://msdn.microsoft.com/en-us/library/ie/ff975241(v=vs.85).aspx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!