feat: updated thumbnail bug fixed
This commit is contained in:
39
app/src/utils/compressImage.ts
Normal file
39
app/src/utils/compressImage.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
export async function compressImage(
|
||||
dataUrl: string,
|
||||
maxWidth = 400,
|
||||
maxHeight = 400
|
||||
): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image();
|
||||
img.src = dataUrl;
|
||||
|
||||
img.onload = () => {
|
||||
const { width, height } = img;
|
||||
|
||||
// Calculate aspect ratio preserving resize
|
||||
let newWidth = width;
|
||||
let newHeight = height;
|
||||
|
||||
if (width > height) {
|
||||
if (width > maxWidth) {
|
||||
newWidth = maxWidth;
|
||||
newHeight = (height * maxWidth) / width;
|
||||
}
|
||||
} else {
|
||||
if (height > maxHeight) {
|
||||
newHeight = maxHeight;
|
||||
newWidth = (width * maxHeight) / height;
|
||||
}
|
||||
}
|
||||
|
||||
const offCanvas = document.createElement("canvas");
|
||||
const ctx = offCanvas.getContext("2d");
|
||||
|
||||
offCanvas.width = newWidth;
|
||||
offCanvas.height = newHeight;
|
||||
|
||||
ctx?.drawImage(img, 0, 0, newWidth, newHeight);
|
||||
resolve(offCanvas.toDataURL("image/png"));
|
||||
};
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user