JavaScript reduce the size and quality of image with based64 encoded code

You can use canvas, put image into it, scale it and get image src with new base64 code.

Here’s the function doing that, it returns promise object, as image needs to be loaded (cached) first before drawing canvas out of it and getting its encoded src.

function resizeBase64Img(base64, width, height) {
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var context = canvas.getContext("2d");
    var deferred = $.Deferred();
    $("<img/>").attr("src", "data:image/gif;base64," + base64).load(function() {
        context.scale(width/this.width,  height/this.height);
        context.drawImage(this, 0, 0); 
        deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));               
    });
    return deferred.promise();    
}

Can be used like this:

resizeBase64Img(oldBase64, 100, 100).then(function(newImg){
    $("body").append(newImg);
});

here’s the jsfiddle

Leave a Comment