downscale pre-ai
This commit is contained in:
@@ -17,13 +17,47 @@
|
||||
let description: string | undefined = $state();
|
||||
let isGenerating = $state(false);
|
||||
|
||||
async function onSelect(file: File) {
|
||||
async function resizeImage(
|
||||
file: File,
|
||||
maxWidth = 300,
|
||||
maxHeight = 300,
|
||||
quality = 0.8
|
||||
): Promise<File> {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
|
||||
let { width, height } = bitmap;
|
||||
|
||||
const scale = Math.min(maxWidth / width, maxHeight / height, 1);
|
||||
|
||||
width = Math.round(width * scale);
|
||||
height = Math.round(height * scale);
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.drawImage(bitmap, 0, 0, width, height);
|
||||
|
||||
const blob = await new Promise<Blob>((resolve) =>
|
||||
canvas.toBlob((blob) => resolve(blob!), "image/jpeg", quality)
|
||||
);
|
||||
|
||||
return new File([blob], file.name, {
|
||||
type: "image/jpeg",
|
||||
lastModified: Date.now()
|
||||
});
|
||||
}
|
||||
|
||||
async function onSelect(file: File) {
|
||||
isGenerating = true;
|
||||
|
||||
const base64 = await fileToBase64(file);
|
||||
const resized = await resizeImage(file, 300, 300, 0.8);
|
||||
|
||||
const base64 = await fileToBase64(resized);
|
||||
|
||||
description = await genDescription(base64);
|
||||
|
||||
isGenerating = false;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user