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

后端 未结 2 1402
暖寄归人
暖寄归人 2020-12-13 11:14

I\'m looking for an elegant way to generate a thumbnail for use with the FileAPI. Currently I get a DataURL representing an image. Problem is, if the image is very large, th

2条回答
  •  萌比男神i
    2020-12-13 11:50

    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

提交回复
热议问题