My blog

Create thumbnails using JavaScript

Create thumbnails using JavaScript

It's easy enough to create read a local file, create a data url (base64 string) and then show it on the page:

var fileSelectHandler = function (file) {
    var reader = new window.FileReader();
    reader.onload = function (evt) {
        $("body").append("<img src='""' />");
document.getElementById("filedrag").addEventListener("drop", fileSelectHandler, false);

However if you're going to have many images, each of which might be several MegaBytes, you get a noticeable performance hit.

The solution is to use Canvas in-memory to draw the image, and get a new data url.

var originalFileDataUrl = "";
var thumbnailMaxWidth = 300;
var thumbnailMaxHeight = 200;

var createThumbnail = function (image) {
    var canvas, ctx, thumbnail, thumbnailScale, thumbnailWidth, thumbnailHeight;
    // create an off-screen canvas
    canvas = document.createElement('canvas');
    ctx = canvas.getContext('2d');

    //Calculate the size of the thumbnail, to best fit within max/width (cropspadding)
    thumbnailScale = (image.width / image.height) > (thumbnailMaxWidth / thumbnailMaxHeight) ?
        thumbnailMaxWidth / image.width :
        thumbnailMaxHeight / image.height;
    thumbnailWidth = image.width * thumbnailScale;
    thumbnailHeight = image.height * thumbnailScale;

    // set its dimension to target size
    canvas.width = thumbnailWidth;
    canvas.height = thumbnailHeight;

    // draw source image into the off-screen canvas:
    ctx.drawImage(image, 0, 0, thumbnailWidth, thumbnailHeight);

    //Draw border (optional)
    ctx.rect(0, 0, thumbnailWidth, thumbnailHeight - 1);
    ctx.strokeStyle = "#555555";

    // encode image to data-uri with base64 version of compressed image
    thumbnail = new Image();
    thumbnail.src = canvas.toDataURL('image/jpeg', 70);
    return thumbnail;

var originalImage = new Image();
originalImage.src = originalFileDataUrl;
originalImage.addEventListener("load", function () {
    var thumbnailImage = createThumbnail();

This should work in IE9+

Share this post
comments powered by Disqus