Resize a Base-64 image in JavaScript without using canvas

A way to avoid the main HTML to be affected is to create an off-screen canvas that is kept out of the DOM-tree.

This will provide a bitmap buffer and native compiled code to encode the image data. It is straight forward to do:

function imageToDataUri(img, width, height) {

    // create an off-screen canvas
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');

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

    // draw source image into the off-screen canvas:
    ctx.drawImage(img, 0, 0, width, height);

    // encode image to data-uri with base64 version of compressed image
    return canvas.toDataURL();
}

If you want to produce a different format than PNG (default) just specify the type like this:

return canvas.toDataURL('image/jpeg', quality);  // quality = [0.0, 1.0]

Worth to note that CORS restrictions applies to toDataURL().

If your app is giving only base64 encoded images (I assume they are data-uri’s with base64 data?) then you need to “load” the image first:

var img = new Image;

img.onload = resizeImage;
img.src = originalDataUriHere;

function resizeImage() {
    var newDataUri = imageToDataUri(this, targetWidth, targetHeight);
    // continue from here...
}

If the source is pure base-64 string simply add a header to it to make it a data-uri:

function base64ToDataUri(base64) {
    return 'data:image/png;base64,' + base64;
}

Just replace the image/png part with the type the base64 string represents (ie. make it an optional argument).

Leave a Comment