Skip to content

Commit 6145812

Browse files
authored
feat: use webp as image prompt format for better compression (#194)
1 parent a7efe45 commit 6145812

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

src/helpers/aiSdkUtils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ export async function fetchResponseFromModelAnthropic(
177177
type: "image",
178178
source: {
179179
type: "base64",
180-
media_type: "image/png",
180+
media_type: "image/webp",
181181
// need to remove the prefix
182182
data: params.imageData.split("base64,")[1],
183183
},

src/shared/images/mergeScreenshots.ts

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ type ExtendedImageData = ImageSourceAttrs & {
1515
export type MergeImageOptionsInput = {
1616
format?: string;
1717
quality?: number;
18+
maxFileSizeMB?: number;
1819
padding?: number;
1920
};
2021

@@ -45,10 +46,31 @@ const getHorizontalLayoutCanvasSize: GetCanvasSize = (images, options) => {
4546
};
4647
};
4748

49+
// Function to get WebP data URL and ensure it's less than 5 MB
50+
function getWebPDataURL(
51+
canvas: HTMLCanvasElement,
52+
maxFileSizeMB: number = 5,
53+
maxQuality = 1,
54+
qualityStep = 0.05,
55+
) {
56+
const maxFileSizeBytes = maxFileSizeMB * 1024 * 1024;
57+
let quality = maxQuality;
58+
let dataURL = canvas.toDataURL("image/webp", quality);
59+
60+
// Check the size of the data URL
61+
while (dataURL.length * 0.75 > maxFileSizeBytes && quality > 0) {
62+
quality -= qualityStep; // Decrease quality
63+
dataURL = canvas.toDataURL("image/webp", quality);
64+
}
65+
66+
return dataURL;
67+
}
68+
4869
// Defaults
4970
const defaultOptions: MergeImageOptions = {
50-
format: "image/png",
51-
quality: 0.92,
71+
format: "image/webp",
72+
quality: 1,
73+
maxFileSizeMB: 5,
5274
padding: 40,
5375
};
5476

@@ -119,6 +141,10 @@ const mergeImages = async (
119141
x += image.img.width + options.padding;
120142
});
121143

144+
if (options.format === "image/webp") {
145+
return getWebPDataURL(canvas, options.maxFileSizeMB, options.quality);
146+
}
147+
122148
return canvas.toDataURL(options.format, options.quality);
123149
});
124150
};

src/state/currentTask.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ export const createCurrentTaskSlice: MyStateCreator<CurrentTaskSlice> = (
314314
knowledge,
315315
);
316316
console.log(labelData);
317-
openBase64InNewTab(imgData, "image/png");
317+
openBase64InNewTab(imgData, "image/webp");
318318
},
319319
prepareLabels: async () => {
320320
const activeTab = await findActiveTab();

0 commit comments

Comments
 (0)