Imageresizing using a canvas

This commit is contained in:
Eric van der Vlist 2023-04-21 21:23:32 +02:00
parent a91230f614
commit e634d13ee5
1 changed files with 25 additions and 12 deletions

View File

@ -4,13 +4,14 @@ export const resize = (imageUrl: string, maxSize: number) => {
img.onload = () => { img.onload = () => {
const currentMaxSize = Math.max(img.width, img.height); const currentMaxSize = Math.max(img.width, img.height);
const ratio = currentMaxSize / maxSize; const ratio = currentMaxSize / maxSize;
const targetWidth = img.width / ratio;
const targetHeight = img.height / ratio;
const nbStepsReal = Math.log2(ratio); const nbStepsReal = Math.log2(ratio);
const nbSteps = Math.floor(nbStepsReal); const nbSteps = Math.floor(nbStepsReal);
const reminder = maxSize - currentMaxSize / 2 ** nbSteps;
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
canvas.width = img.width / 2; canvas.width = img.width;
canvas.height = img.height / 2; canvas.height = img.height;
const canvasCtx = canvas.getContext('2d'); const canvasCtx = canvas.getContext('2d');
let src: any = img; let src: any = img;
@ -19,27 +20,39 @@ export const resize = (imageUrl: string, maxSize: number) => {
for (let i = 0; i < nbSteps; i++) { for (let i = 0; i < nbSteps; i++) {
width = width / 2; width = width / 2;
height = height / 2; height = height / 2;
canvasCtx?.drawImage(src, 0, 0, width, height); canvasCtx?.drawImage(src, 0, 0, canvas.width / 2, canvas.height / 2);
src = canvas; src = canvas;
console.log({
caller: 'resize',
width,
height,
targetHeight,
targetWidth,
i,
});
} }
const finalCanvas = document.createElement('canvas'); const finalCanvas = document.createElement('canvas');
finalCanvas.height = height; finalCanvas.height = targetHeight;
finalCanvas.width = width; finalCanvas.width = targetWidth;
const finalCanvasCtx = finalCanvas.getContext('2d'); const finalCanvasCtx = finalCanvas.getContext('2d');
finalCanvasCtx?.drawImage( finalCanvasCtx?.drawImage(
canvas, canvas,
0, 0,
0, 0,
width * 4,
height * 4,
0,
0,
width, width,
height height,
0,
0,
targetWidth,
targetHeight
); );
resolver(finalCanvas.toDataURL('image/jpeg')); const imageUrl = finalCanvas.toDataURL('image/jpeg');
canvas.remove();
finalCanvas.remove();
resolver(imageUrl);
}; };
img.src = imageUrl; img.src = imageUrl;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {