enh: image compression

This commit is contained in:
Timothy Jaeryang Baek
2024-12-24 23:28:14 -07:00
parent 591aac5e16
commit 326514be4e
4 changed files with 160 additions and 7 deletions

View File

@@ -14,6 +14,7 @@ function escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export const replaceTokens = (content, sourceIds, char, user) => {
const charToken = /{{char}}/gi;
const userToken = /{{user}}/gi;
@@ -189,6 +190,72 @@ export const canvasPixelTest = () => {
return true;
};
export const compressImage = async (imageUrl, maxWidth, maxHeight) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
// Maintain aspect ratio while resizing
if (maxWidth && maxHeight) {
// Resize with both dimensions defined (preserves aspect ratio)
if (width <= maxWidth && height <= maxHeight) {
resolve(imageUrl);
return;
}
if (width / height > maxWidth / maxHeight) {
height = Math.round((maxWidth * height) / width);
width = maxWidth;
} else {
width = Math.round((maxHeight * width) / height);
height = maxHeight;
}
} else if (maxWidth) {
// Only maxWidth defined
if (width <= maxWidth) {
resolve(imageUrl);
return;
}
height = Math.round((maxWidth * height) / width);
width = maxWidth;
} else if (maxHeight) {
// Only maxHeight defined
if (height <= maxHeight) {
resolve(imageUrl);
return;
}
width = Math.round((maxHeight * width) / height);
height = maxHeight;
}
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
context.drawImage(img, 0, 0, width, height);
// Get compressed image URL
const compressedUrl = canvas.toDataURL();
resolve(compressedUrl);
};
img.onerror = (error) => reject(error);
img.src = imageUrl;
});
}
export const generateInitialsImage = (name) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');