Last active
January 28, 2024 17:21
-
-
Save Mhmdrza/c31357897164de72a640fa5dd65d3f04 to your computer and use it in GitHub Desktop.
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
async function compressAndBase64(file, { | |
quality = 91, | |
scaleFactor = Math.log(file.size) / 13, // scale down images over 1MB | |
} = {}) { | |
return new Promise((res, rej)=>{ | |
const img = new Image(); | |
img.src = URL.createObjectURL(file); | |
img.onload = function() { | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
canvas.height = this.naturalHeight / scaleFactor; | |
canvas.width = this.naturalWidth / scaleFactor; | |
ctx.scale(1 / scaleFactor, 1 / scaleFactor); | |
ctx.drawImage(this, 0, 0); | |
URL.revokeObjectURL(file); | |
res(canvas.toDataURL("image/jpeg", quality/100)); | |
}; | |
img.onerror = rej; | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment