ai-chatbot/lib/canvas/batch-instruction-output.ts

46 lines
2.0 KiB
TypeScript

import "server-only";
import { randomUUID } from "node:crypto";
import sharp from "sharp";
import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service";
import { uploadFile } from "@/lib/storage/service";
export async function padImageToSquare(bytes: Buffer) {
const source = sharp(bytes).autoOrient();
const metadata = await source.metadata();
const { width, height } = metadata.autoOrient;
if (!width || !height) throw new Error("无法读取生成图尺寸");
if (width === height) return null;
const size = Math.max(width, height);
const left = Math.floor((size - width) / 2);
const top = Math.floor((size - height) / 2);
const { data, info } = await source.clone().ensureAlpha().raw().toBuffer({ resolveWithObject: true });
const corners = [0, (width - 1) * info.channels, (height - 1) * width * info.channels, (width * height - 1) * info.channels];
const sample = (channel: number) =>
Math.round(corners.reduce((sum, offset) => sum + data[offset + channel], 0) / corners.length);
const background = { r: sample(0), g: sample(1), b: sample(2), alpha: sample(3) / 255 };
return source.extend({ left, right: size - width - left, top, bottom: size - height - top, background })
.keepIccProfile()
.png()
.toBuffer();
}
export async function squareBatchInstructionOutput(image: { originalUrl: string; thumbnailUrl: string }) {
const bytes = await fetchImageBufferFromUrl(image.originalUrl);
const padded = await padImageToSquare(bytes);
if (!padded) return image;
const thumbnail = await sharp(padded).resize(512, 512, { withoutEnlargement: true }).png().toBuffer();
const id = randomUUID();
const upload = (name: string, file: Buffer) => uploadFile(
name,
new Uint8Array(file).buffer,
{ preferQiniuForm: true },
);
const [original, preview] = await Promise.all([
upload(`batch-instruction-${id}.png`, padded),
upload(`batch-instruction-${id}-thumb.png`, thumbnail),
]);
return { ...image, originalUrl: original.url, thumbnailUrl: preview.url };
}