mirror of
https://github.com/open-webui/open-webui
synced 2025-06-26 18:26:48 +00:00
enh: image compression
This commit is contained in:
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user