Skip to content

Commit

Permalink
feat: use webp as image prompt format for better compression (#194)
Browse files Browse the repository at this point in the history
  • Loading branch information
mondaychen authored Jun 25, 2024
1 parent a7efe45 commit 6145812
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/helpers/aiSdkUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export async function fetchResponseFromModelAnthropic(
type: "image",
source: {
type: "base64",
media_type: "image/png",
media_type: "image/webp",
// need to remove the prefix
data: params.imageData.split("base64,")[1],
},
Expand Down
30 changes: 28 additions & 2 deletions src/shared/images/mergeScreenshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type ExtendedImageData = ImageSourceAttrs & {
export type MergeImageOptionsInput = {
format?: string;
quality?: number;
maxFileSizeMB?: number;
padding?: number;
};

Expand Down Expand Up @@ -45,10 +46,31 @@ const getHorizontalLayoutCanvasSize: GetCanvasSize = (images, options) => {
};
};

// Function to get WebP data URL and ensure it's less than 5 MB
function getWebPDataURL(
canvas: HTMLCanvasElement,
maxFileSizeMB: number = 5,
maxQuality = 1,
qualityStep = 0.05,
) {
const maxFileSizeBytes = maxFileSizeMB * 1024 * 1024;
let quality = maxQuality;
let dataURL = canvas.toDataURL("image/webp", quality);

// Check the size of the data URL
while (dataURL.length * 0.75 > maxFileSizeBytes && quality > 0) {
quality -= qualityStep; // Decrease quality
dataURL = canvas.toDataURL("image/webp", quality);
}

return dataURL;
}

// Defaults
const defaultOptions: MergeImageOptions = {
format: "image/png",
quality: 0.92,
format: "image/webp",
quality: 1,
maxFileSizeMB: 5,
padding: 40,
};

Expand Down Expand Up @@ -119,6 +141,10 @@ const mergeImages = async (
x += image.img.width + options.padding;
});

if (options.format === "image/webp") {
return getWebPDataURL(canvas, options.maxFileSizeMB, options.quality);
}

return canvas.toDataURL(options.format, options.quality);
});
};
Expand Down
2 changes: 1 addition & 1 deletion src/state/currentTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ export const createCurrentTaskSlice: MyStateCreator<CurrentTaskSlice> = (
knowledge,
);
console.log(labelData);
openBase64InNewTab(imgData, "image/png");
openBase64InNewTab(imgData, "image/webp");
},
prepareLabels: async () => {
const activeTab = await findActiveTab();
Expand Down

0 comments on commit 6145812

Please sign in to comment.