Created
December 1, 2022 16:44
-
-
Save matiasmicheletto/383c95899a481a7a89ad0a8ae82ef2c4 to your computer and use it in GitHub Desktop.
Resize a base64 image with javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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