Attempt to scale using a canvas element

This commit is contained in:
vdv committed 2023-04-21 18:53:38 +02:00
1 parent 4df529abb7
commit a91230f614
2 files changed
+51 -1

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
export const resize = (imageUrl: string, maxSize: number) => {
let resolver = (resizedImageUrl: any) => {};
const img = document.createElement('img');
img.onload = () => {
const currentMaxSize = Math.max(img.width, img.height);
const ratio = currentMaxSize / maxSize;
const nbStepsReal = Math.log2(ratio);
const nbSteps = Math.floor(nbStepsReal);
const reminder = maxSize - currentMaxSize / 2 ** nbSteps;
const canvas = document.createElement('canvas');
canvas.width = img.width / 2;
canvas.height = img.height / 2;
const canvasCtx = canvas.getContext('2d');
let src: any = img;
let width = img.width;
let height = img.height;
for (let i = 0; i < nbSteps; i++) {
width = width / 2;
height = height / 2;
canvasCtx?.drawImage(src, 0, 0, width, height);
src = canvas;
}
const finalCanvas = document.createElement('canvas');
finalCanvas.height = height;
finalCanvas.width = width;
const finalCanvasCtx = finalCanvas.getContext('2d');
finalCanvasCtx?.drawImage(
canvas,
0,
0,
width * 4,
height * 4,
0,
0,
width,
height
);
resolver(finalCanvas.toDataURL('image/jpeg'));
};
img.src = imageUrl;
return new Promise((resolve, reject) => {
resolver = resolve;
});
};