Created
June 18, 2024 14:11
-
-
Save graue/ed5a3aef75ac1c8b8e1f547be2257ddb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// utility to shrink/recompress an image if it's big or non-JPEG | |
// input is a Blob (superclass of File, so File also ok), output a Blob | |
const MAX_DIM = 1536; | |
const QUALITY = 0.80; | |
export default function shrinkImage(blob) { | |
return new Promise((resolve, reject) => { | |
const url = URL.createObjectURL(blob); | |
const img = document.createElement('img'); | |
img.addEventListener('load', () => { | |
URL.revokeObjectURL(url); | |
const origWidth = img.naturalWidth; | |
const origHeight = img.naturalHeight; | |
if (blob.type === 'image/jpeg' && origWidth <= MAX_DIM | |
&& origHeight <= MAX_DIM) { | |
// no need to recompress | |
resolve(blob); | |
return; | |
} | |
const scaleFactor = Math.min( | |
MAX_DIM / Math.max(origWidth, origHeight), | |
1, // in case of solely converting formats, don't *increase* size. | |
); | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
canvas.width = origWidth * scaleFactor; | |
canvas.height = origHeight * scaleFactor; | |
try { | |
ctx.drawImage(img, 0, 0, canvas.width, canvas.height); | |
canvas.toBlob((newBlob) => { | |
if (!newBlob) reject(new Error("can't compress")); | |
resolve(newBlob); | |
}, 'image/jpeg', QUALITY); | |
} catch(err) { | |
reject(err); | |
} | |
}); | |
img.addEventListener('error', (evt) => { | |
URL.revokeObjectURL(url); | |
reject(evt); | |
}); | |
img.src = url; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment