import "server-only"; import { randomUUID } from "node:crypto"; import sharp from "sharp"; import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service"; import { buildS3PublicUrl, resolveS3UploadTarget, uploadFile } from "@/lib/storage/service"; import type { BatchInstructionSize } from "./batch-instruction-size"; async function sampleBackground(source: sharp.Sharp) { const { data, info } = await source.clone().toColourspace("srgb").ensureAlpha().raw().toBuffer({ resolveWithObject: true }); const { width, height } = info; 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); return { r: sample(0), g: sample(1), b: sample(2), alpha: sample(3) / 255 }; } export async function padImageToSquare(bytes: Buffer) { const source = sharp(bytes).autoOrient(); const { width, height } = (await source.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 background = await sampleBackground(source); return source.extend({ left, right: size - width - left, top, bottom: size - height - top, background }) .keepIccProfile() .png() .toBuffer(); } export async function fitBatchInstructionImage(bytes: Buffer, size: BatchInstructionSize) { const source = sharp(bytes, { limitInputPixels: 40_000_000 }).autoOrient(); const background = await sampleBackground(source); return source.resize({ ...size, fit: "contain", background }).keepIccProfile().png().toBuffer(); } async function saveBatchInstructionImage(image: Buffer) { const thumbnail = await sharp(image).resize(512, 512, { fit: "inside", 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`, image), upload(`batch-instruction-${id}-thumb.png`, thumbnail), ]); return { originalUrl: original.url, thumbnailUrl: preview.url }; } export async function formatBatchInstructionOutput( generated: T, size?: BatchInstructionSize, ) { const bytes = await fetchImageBufferFromUrl(generated.originalUrl); const output = size ? await fitBatchInstructionImage(bytes, size) : await padImageToSquare(bytes); return output ? { ...generated, ...await saveBatchInstructionImage(output) } : generated; } export async function resizeBatchInstructionInput(source: string, size: BatchInstructionSize) { const target = await resolveS3UploadTarget(); if (!target) throw new Error("图片存储暂不可用"); const base = new URL(buildS3PublicUrl(target.config, "")); const image = new URL(source); if (image.origin !== base.origin || !image.pathname.startsWith(base.pathname) || image.pathname === base.pathname) { throw new Error("请重新上传待调整尺寸的图片"); } const response = await fetch(image, { redirect: "error", signal: AbortSignal.timeout(20_000) }); if (!response.ok) throw new Error("无法读取待调整尺寸的图片"); const output = await fitBatchInstructionImage(Buffer.from(await response.arrayBuffer()), size); return await saveBatchInstructionImage(output); }