Created
February 22, 2025 20:20
-
-
Save EpicKiwi/ea987e070e8b1ef8e01994166a7de112 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
| // sourceImage can be any File or Blob | |
| async resizeImage(sourceImage){ | |
| let el = document.createElement("img") | |
| let prom = new Promise( (res, rej) => { | |
| el.addEventListener("load", res) | |
| el.addEventListener("error", rej) | |
| }) | |
| el.src = URL.createObjectURL(sourceImage) | |
| await prom | |
| let width = 0; | |
| let height = 0; | |
| if(el.naturalWidth > el.naturalHeight) { | |
| width = Math.min(1920, el.naturalWidth); | |
| height = (el.naturalHeight * width) / el.naturalWidth | |
| } else { | |
| height = Math.min(1920, el.naturalHeight); | |
| width = (el.naturalWidth * height) / el.naturalHeight | |
| } | |
| let canvas = new OffscreenCanvas(width, height); | |
| let ctx = canvas.getContext("2d") | |
| ctx.drawImage(el, 0, 0, width, height) | |
| let blob = await canvas.convertToBlob({ | |
| type: "image/jpeg", | |
| quality: 0.9 | |
| }) | |
| URL.revokeObjectURL(el.src) | |
| return blob | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment