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
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);
});