From e7330ddcdab549731e026e6049898ea7c6ae6f0c Mon Sep 17 00:00:00 2001 From: Daniel Rochetti Date: Tue, 5 Mar 2024 19:59:18 -0800 Subject: [PATCH] fix: canvas final size --- lib/image.ts | 50 +++++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/lib/image.ts b/lib/image.ts index 90c3615..e470f25 100644 --- a/lib/image.ts +++ b/lib/image.ts @@ -1,7 +1,4 @@ -export async function resizeImage( - file: File, - max: number = 1024, -): Promise { +export async function resizeImage(file: File, max: number = 1024): Promise { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); @@ -12,31 +9,18 @@ export async function resizeImage( const image = await loadImage(file); const targetSize = Math.min(max, Math.max(image.width, image.height)); - console.log("targetSize", targetSize); + const targetWidth = - image.width > image.height - ? targetSize - : Math.round((image.width / image.height) * targetSize); + image.width > image.height ? targetSize : Math.round((image.width / image.height) * targetSize); const targetHeight = - image.height > image.width - ? targetSize - : Math.round((image.height / image.width) * targetSize); + image.height > image.width ? targetSize : Math.round((image.height / image.width) * targetSize); - ctx.drawImage(image, 0, 0, targetWidth, targetHeight); + canvas.width = targetWidth; + canvas.height = targetHeight; - return new Promise((resolve, reject) => { - canvas.toBlob( - (blob) => { - if (!blob) { - reject(new Error("Failed to convert canvas to blob")); - return; - } - resolve(blob); - }, - "image/jpeg", - 0.7, - ); - }); + ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, targetWidth, targetHeight); + + return await canvasToImage(canvas); } async function loadImage(file: File): Promise { @@ -52,3 +36,19 @@ async function loadImage(file: File): Promise { reader.readAsDataURL(file); }); } + +async function canvasToImage(canvas: HTMLCanvasElement): Promise { + return new Promise((resolve, reject) => { + canvas.toBlob( + (blob) => { + if (!blob) { + reject(new Error("Failed to convert canvas to blob")); + return; + } + resolve(blob); + }, + "image/jpeg", + 0.7, + ); + }); +}