Skip to content

Instantly share code, notes, and snippets.

@Mhmdrza
Last active January 28, 2024 17:21
Show Gist options
  • Save Mhmdrza/c31357897164de72a640fa5dd65d3f04 to your computer and use it in GitHub Desktop.
Save Mhmdrza/c31357897164de72a640fa5dd65d3f04 to your computer and use it in GitHub Desktop.
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