Created
September 14, 2021 10:44
-
-
Save earlgreyxxx/1b37f2d633d43d8525dd98160eaaf1ef 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
importScripts('./node_modules/comlink/dist/umd/comlink.min.js'); | |
async function resizer(file,offscreencanvas,max) | |
{ | |
let width = max,height = max; | |
let img = await createImageBitmap(file); | |
let ratio = img.width / img.height; | |
if(ratio < 1 && img.width <= max) | |
return file; | |
if(ratio >= 1 && img.height <= max) | |
return file; | |
// calculate resized image width/height | |
if(img.width > img.height) | |
width = height * img.width / img.height; | |
else if(img.width < img.height) | |
height = width * img.height / img.width; | |
offscreencanvas.width = width; | |
offscreencanvas.height = height; | |
let ctx = offscreencanvas.getContext('2d'); | |
// clear canvas rect | |
ctx.clearRect(0,0,width,height); | |
// draw image to canvas | |
ctx.drawImage( | |
img, | |
0, | |
0, | |
img.width, | |
img.height, | |
0, | |
0, | |
width, | |
height | |
); | |
return new File([await getBlobFromCanvas(offscreencanvas,file.type)],file.name,{type: file.type,lastModified: file.lastModified}); | |
} | |
function getBlobFromCanvas(offscreencanvas,type,quality) | |
{ | |
type = type || 'image/png'; | |
quality = quality || 0.8; | |
return offscreencanvas.convertToBlob({'type': type,'quality': quality}); | |
} | |
Comlink.expose(resizer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment