Skip to content

Instantly share code, notes, and snippets.

@EpicKiwi
Created February 22, 2025 20:20
Show Gist options
  • Select an option

  • Save EpicKiwi/ea987e070e8b1ef8e01994166a7de112 to your computer and use it in GitHub Desktop.

Select an option

Save EpicKiwi/ea987e070e8b1ef8e01994166a7de112 to your computer and use it in GitHub Desktop.
// 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