Skip to content

Commit 9c268d4

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

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,
@@ -761,6 +762,9 @@
761762
// Compress the image if settings or config require it
762763
imageUrl = await compressImageHandler(imageUrl, $settings, $config);
763764
765+
// Convert to WebP at 0.9 quality for smaller payload
766+
imageUrl = await convertToWebP(imageUrl, 0.9);
767+
764768
if ($temporaryChatEnabled) {
765769
files = [
766770
...files,
@@ -771,9 +775,13 @@
771775
];
772776
} else {
773777
const blob = await (await fetch(imageUrl)).blob();
774-
const compressedFile = new File([blob], file.name, { type: file.type });
778+
const webpFile = new File(
779+
[blob],
780+
file.name.replace(/\.[^.]+$/, '.webp'),
781+
{ type: 'image/webp' }
782+
);
775783
776-
uploadFileHandler(compressedFile, false);
784+
uploadFileHandler(webpFile, false);
777785
}
778786
};
779787

src/lib/utils/index.ts

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

0 commit comments

Comments
 (0)