Skip to content

Commit fb193e1

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

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,
@@ -763,6 +764,9 @@
763764
// Compress the image if settings or config require it
764765
imageUrl = await compressImageHandler(imageUrl, $settings, $config);
765766
767+
// Convert to WebP at 0.9 quality for smaller payload
768+
imageUrl = await convertToWebP(imageUrl, 0.9);
769+
766770
if ($temporaryChatEnabled) {
767771
files = [
768772
...files,
@@ -773,9 +777,13 @@
773777
];
774778
} else {
775779
const blob = await (await fetch(imageUrl)).blob();
776-
const compressedFile = new File([blob], file.name, { type: file.type });
780+
const webpFile = new File(
781+
[blob],
782+
file.name.replace(/\.[^.]+$/, '.webp'),
783+
{ type: 'image/webp' }
784+
);
777785
778-
uploadFileHandler(compressedFile, false);
786+
uploadFileHandler(webpFile, false);
779787
}
780788
};
781789

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)