Skip to content

Instantly share code, notes, and snippets.

@matiasmicheletto
Created December 1, 2022 16:44
Show Gist options
  • Save matiasmicheletto/383c95899a481a7a89ad0a8ae82ef2c4 to your computer and use it in GitHub Desktop.
Save matiasmicheletto/383c95899a481a7a89ad0a8ae82ef2c4 to your computer and use it in GitHub Desktop.
Resize a base64 image with javascript
const imgResize = (base64, factor) => {
return new Promise((resolve, reject) => {
const watchdog = setTimeout(()=>{
reject(new Error("TIMEOUT"));
}, 5000); // If image loading takes too long
const canvas = document.createElement("canvas");
const img = new Image();
img.onload = function () {
clearTimeout(watchdog);
canvas.width = Math.round(img.width*factor);
canvas.height = Math.round(img.height*factor);
const ctx = canvas.getContext("2d");
ctx.scale(factor, factor);
ctx.drawImage(img, 0, 0);
resolve(canvas.toDataURL());
};
img.src = base64;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment