I have the based64 encoded code of an image. Now I want to reduce the size and quality of the image. How can I do this in JavaScript or jQuery?
Resolve here
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
A non-jquery solution based on @paulitto 's answer for future googlers like me:
/**
* Resize a base 64 Image
* @param {String} base64 - The base64 string (must include MIME type)
* @param {Number} newWidth - The width of the image in pixels
* @param {Number} newHeight - The height of the image in pixels
*/
function resizeBase64Img(base64, newWidth, newHeight) {
return new Promise((resolve, reject)=>{
var canvas = document.createElement("canvas");
canvas.style.width = newWidth.toString()+"px";
canvas.style.height = newHeight.toString()+"px";
let context = canvas.getContext("2d");
let img = document.createElement("img");
img.src = base64;
img.onload = function () {
context.scale(newWidth/img.width, newHeight/img.height);
context.drawImage(img, 0, 0);
resolve(canvas.toDataURL());
}
});
}
Use it like:
resizeBase64Img(basedata, 50, 50).then((result)=>{
console.log("After resize: "+result);
});