Skip to content

Commit ac1ea74

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

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,
@@ -773,6 +774,9 @@
773774
// Compress the image if settings or config require it
774775
imageUrl = await compressImageHandler(imageUrl, $settings, $config);
775776
777+
// Convert to WebP at 0.9 quality for smaller payload
778+
imageUrl = await convertToWebP(imageUrl, 0.9);
779+
776780
if ($temporaryChatEnabled) {
777781
files = [
778782
...files,
@@ -783,9 +787,13 @@
783787
];
784788
} else {
785789
const blob = await (await fetch(imageUrl)).blob();
786-
const compressedFile = new File([blob], file.name, { type: file.type });
790+
const webpFile = new File(
791+
[blob],
792+
file.name.replace(/\.[^.]+$/, '.webp'),
793+
{ type: 'image/webp' }
794+
);
787795
788-
uploadFileHandler(compressedFile, false);
796+
uploadFileHandler(webpFile, false);
789797
}
790798
};
791799

src/lib/utils/index.ts

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

0 commit comments

Comments
 (0)