Skip to content

Commit 05d13d9

Browse files
Algorithm5838github-actions[bot]
authored andcommitted
feat: convert user-attached chat images to WebP at 0.9 quality
1 parent f73188d commit 05d13d9

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

src/lib/components/chat/MessageInput.svelte

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
import {
4141
convertHeicToJpeg,
4242
compressImage,
43+
convertToWebP,
4344
createMessagesList,
4445
extractContentFromFile,
4546
extractCurlyBraceWords,
@@ -768,6 +769,9 @@
768769
// Compress the image if settings or config require it
769770
imageUrl = await compressImageHandler(imageUrl, $settings, $config);
770771
772+
// Convert to WebP at 0.9 quality for smaller payload
773+
imageUrl = await convertToWebP(imageUrl, 0.9);
774+
771775
if ($temporaryChatEnabled) {
772776
files = [
773777
...files,
@@ -778,9 +782,13 @@
778782
];
779783
} else {
780784
const blob = await (await fetch(imageUrl)).blob();
781-
const compressedFile = new File([blob], file.name, { type: file.type });
785+
const webpFile = new File(
786+
[blob],
787+
file.name.replace(/\.[^.]+$/, '.webp'),
788+
{ type: 'image/webp' }
789+
);
782790
783-
uploadFileHandler(compressedFile, false);
791+
uploadFileHandler(webpFile, false);
784792
}
785793
};
786794

src/lib/utils/index.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,20 @@ export const compressImage = async (imageUrl, maxWidth, maxHeight) => {
370370
img.src = imageUrl;
371371
});
372372
};
373+
export const convertToWebP = (imageUrl: string, quality = 0.9): Promise<string> =>
374+
new Promise((resolve, reject) => {
375+
const img = new Image();
376+
img.onload = () => {
377+
const canvas = document.createElement('canvas');
378+
canvas.width = img.naturalWidth;
379+
canvas.height = img.naturalHeight;
380+
canvas.getContext('2d')!.drawImage(img, 0, 0);
381+
resolve(canvas.toDataURL('image/webp', quality));
382+
};
383+
img.onerror = reject;
384+
img.src = imageUrl;
385+
});
386+
373387
export const generateInitialsImage = (name) => {
374388
const canvas = document.createElement('canvas');
375389
const ctx = canvas.getContext('2d');

0 commit comments

Comments
 (0)