Skip to content

Commit fe8daa3

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

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,
@@ -762,6 +763,9 @@
762763
// Compress the image if settings or config require it
763764
imageUrl = await compressImageHandler(imageUrl, $settings, $config);
764765
766+
// Convert to WebP at 0.9 quality for smaller payload
767+
imageUrl = await convertToWebP(imageUrl, 0.9);
768+
765769
if ($temporaryChatEnabled) {
766770
files = [
767771
...files,
@@ -772,9 +776,13 @@
772776
];
773777
} else {
774778
const blob = await (await fetch(imageUrl)).blob();
775-
const compressedFile = new File([blob], file.name, { type: file.type });
779+
const webpFile = new File(
780+
[blob],
781+
file.name.replace(/\.[^.]+$/, '.webp'),
782+
{ type: 'image/webp' }
783+
);
776784
777-
uploadFileHandler(compressedFile, false);
785+
uploadFileHandler(webpFile, false);
778786
}
779787
};
780788

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)