Merge pull request '图片处理使用七牛链接交付' (#121) from codex/batch-enhance-qiniu into main

This commit is contained in:
WuYongJie 2026-11-24 17:44:47 +08:00
commit e4fcfee16b
17 changed files with 132 additions and 219 deletions

View File

@ -143,57 +143,28 @@ export default function GalleryPage() {
try { try {
toast.info("正在处理抠图,请稍候..."); toast.info("正在处理抠图,请稍候...");
// 获取原图并转换为Base64 const imageUrl = new URL(image.url, window.location.origin).href;
const response = await fetch(image.url); const response = await fetch("/api/rmbg", {
const blob = await response.blob(); method: "POST",
const reader = new FileReader(); headers: { "Content-Type": "application/json" },
body: JSON.stringify({
reader.onloadend = async () => { imageUrl,
try { prompt: `抠图处理 - ${image.alt}`,
const base64Data = (reader.result as string).split(",")[1]; chatId: image.chatId,
messageId: image.messageId,
// 调用抠图API includeBase64: false,
const rmbgResponse = await fetch("/api/rmbg", { }),
method: "POST", });
headers: { const result = await response.json();
"Content-Type": "application/json", if (!response.ok || !result.success) {
}, throw new Error(result.error || result.detail || "抠图失败");
body: JSON.stringify({ }
image_base64: base64Data, await fetchImages(pagination.page);
prompt: `抠图处理 - ${image.alt}`, toast.success(`抠图完成!处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`);
chatId: image.chatId,
messageId: image.messageId,
}),
});
if (!rmbgResponse.ok) {
const error = await rmbgResponse.json();
throw new Error(error.error || error.detail || "抠图失败");
}
const result = await rmbgResponse.json();
// 刷新相册列表以显示新图片
await fetchImages(pagination.page);
toast.success(`抠图完成!处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`);
} catch (error) {
console.error("[抠图] 错误:", error);
toast.error(error instanceof Error ? error.message : "抠图处理失败");
} finally {
setProcessingImageId(null);
}
};
reader.onerror = () => {
toast.error("图片读取失败");
setProcessingImageId(null);
};
reader.readAsDataURL(blob);
} catch (error) { } catch (error) {
console.error("[抠图] 错误:", error); console.error("[抠图] 错误:", error);
toast.error(error instanceof Error ? error.message : "抠图处理失败"); toast.error(error instanceof Error ? error.message : "抠图处理失败");
} finally {
setProcessingImageId(null); setProcessingImageId(null);
} }
}; };
@ -208,51 +179,23 @@ export default function GalleryPage() {
try { try {
toast.info("正在处理图片变清晰,请稍候..."); toast.info("正在处理图片变清晰,请稍候...");
// 获取原图并转换为Base64 const imageUrl = new URL(image.url, window.location.origin).href;
const response = await fetch(image.url); const prompt = `图片变清晰处理 - ${image.alt}`;
const blob = await response.blob(); const { chatId, messageId } = image;
const reader = new FileReader(); const result = await requestLongTaskResult({
endpoint: "/api/enhance",
reader.onloadend = async () => { payload: { imageUrl, prompt, chatId, messageId, includeBase64: false },
try { pollingParams: { sourceImageUrl: imageUrl, prompt, chatId, messageId, includeBase64: "false" },
const base64Data = (reader.result as string).split(",")[1]; });
if (!result?.success) {
const result = await requestLongTaskResult({ throw new Error(result?.error || result?.detail || "变清晰处理失败");
endpoint: "/api/enhance", }
payload: { await fetchImages(pagination.page);
image_base64: base64Data, toast.success(`变清晰完成!处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`);
prompt: `图片变清晰处理 - ${image.alt}`,
chatId: image.chatId,
messageId: image.messageId,
},
pollingParams: {
prompt: `图片变清晰处理 - ${image.alt}`,
chatId: image.chatId,
messageId: image.messageId,
},
});
// 刷新相册列表以显示新图片
await fetchImages(pagination.page);
toast.success(`变清晰完成!处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`);
} catch (error) {
console.error("[变清晰] 错误:", error);
toast.error(error instanceof Error ? error.message : "变清晰处理失败");
} finally {
setEnhancingImageId(null);
}
};
reader.onerror = () => {
toast.error("图片读取失败");
setEnhancingImageId(null);
};
reader.readAsDataURL(blob);
} catch (error) { } catch (error) {
console.error("[变清晰] 错误:", error); console.error("[变清晰] 错误:", error);
toast.error(error instanceof Error ? error.message : "变清晰处理失败"); toast.error(error instanceof Error ? error.message : "变清晰处理失败");
} finally {
setEnhancingImageId(null); setEnhancingImageId(null);
} }
}; };

View File

@ -110,6 +110,7 @@ export async function POST(request: NextRequest) {
const result = await executeRmbgJob({ const result = await executeRmbgJob({
userId: session.user.id, userId: session.user.id,
imageBuffer, imageBuffer,
includeBase64: false,
prompt, prompt,
skipGallerySave: true, skipGallerySave: true,
}); });

View File

@ -45,6 +45,7 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ return NextResponse.json({
success: true, success: true,
...result, ...result,
image_base64: body.includeBase64 === false ? undefined : result.image_base64,
}); });
} catch (error) { } catch (error) {
if (error instanceof ResizeServiceError) { if (error instanceof ResizeServiceError) {

View File

@ -107,6 +107,7 @@ export function AngleEditDialog({
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
image_url: imageUrl, image_url: imageUrl,
includeBase64: false,
horizontal_angle: cameraState.azimuth, // 0-360 度 horizontal_angle: cameraState.azimuth, // 0-360 度
vertical_angle: cameraState.elevation, // -30 到 90 度 vertical_angle: cameraState.elevation, // -30 到 90 度
zoom: cameraState.distance, // 0-10 zoom: cameraState.distance, // 0-10

View File

@ -885,87 +885,48 @@ export function ImageAnnotator({
setActions([]); setActions([]);
}; };
// 将图片URL转换为Base64(获取原图数据) const resolveProcessingImageUrl = async (url: string): Promise<string> => {
const imageUrlToBase64 = async (url: string): Promise<string> => { const source = new URL(url, window.location.origin);
// 如果已经是data URL,直接返回 if (source.protocol === "https:" || source.protocol === "http:") {
if (url.startsWith("data:")) { return source.href;
return url.split(",")[1];
} }
// 如果是HTTP URL,需要先fetch获取 const response = await fetch(source.href);
const response = await fetch(url); if (!response.ok) throw new Error("无法读取待处理图片");
if (!response.ok) {
throw new Error(
`获取原图失败: ${response.status} ${response.statusText}`
);
}
const blob = await response.blob(); const blob = await response.blob();
const extension = blob.type === "image/jpeg" ? "jpg" : blob.type.split("/")[1] || "png";
return new Promise((resolve, reject) => { const file = new File([blob], `source-${Date.now()}.${extension}`, { type: blob.type });
const reader = new FileReader(); return (await uploadImageFile(file)).url;
reader.onloadend = () => {
const base64String = (reader.result as string).split(",")[1];
resolve(base64String);
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}; };
// 抠图功能
const handleRemoveBackground = async () => { const handleRemoveBackground = async () => {
if (!image || !originalImageUrl) return; if (!image || !originalImageUrl) return;
setIsRemovingBg(true); setIsRemovingBg(true);
try { try {
const input = /^https?:\/\//i.test(originalImageUrl) const imageUrl = await resolveProcessingImageUrl(originalImageUrl);
? { imageUrl: originalImageUrl }
: { image_base64: await imageUrlToBase64(originalImageUrl) };
// 调用抠图API
const response = await fetch("/api/rmbg", { const response = await fetch("/api/rmbg", {
method: "POST", method: "POST",
headers: { headers: { "Content-Type": "application/json" },
"Content-Type": "application/json",
},
body: JSON.stringify({ body: JSON.stringify({
...input, imageUrl,
prompt: "画图标注-抠图处理", // 可选:添加提示词 prompt: "画图标注-抠图处理",
includeBase64: false,
}), }),
}); });
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || "抠图失败");
}
const result = await response.json(); const result = await response.json();
const resultUrl = result.original_url || result.thumbnail_url;
if (result.success && result.image_base64) { if (!response.ok || !result.success || !resultUrl) {
// 保存处理后的图片URL和Base64(优先使用original_url,确保下载的是原图)
logger.info("rmbg_completed", {
hasOriginalUrl: !!result.original_url,
hasThumbnailUrl: !!result.thumbnail_url,
base64Length: String(result.image_base64 || "").length,
});
if (result.original_url) {
setProcessedImageUrl(result.original_url);
} else if (result.thumbnail_url) {
logger.warn("rmbg_original_url_missing", { hasThumbnailUrl: true });
setProcessedImageUrl(result.thumbnail_url);
} else {
logger.warn("rmbg_image_url_missing");
setProcessedImageUrl(null);
}
setProcessedImageBase64(result.image_base64);
setProcessType("rmbg");
toast.success(
`抠图完成!图片已保存到相册。处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`
);
} else {
throw new Error(result.error || result.detail || "抠图处理失败"); throw new Error(result.error || result.detail || "抠图处理失败");
} }
setProcessedImageUrl(resultUrl);
setProcessedImageBase64(null);
setProcessType("rmbg");
toast.success(
`抠图完成!图片已保存到相册。处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`
);
} catch (error) { } catch (error) {
logger.error("rmbg_failed", error); logger.error("rmbg_failed", error);
toast.error( toast.error(
@ -1027,62 +988,30 @@ export function ImageAnnotator({
} }
}; };
// 变清晰处理
const handleEnhance = async () => { const handleEnhance = async () => {
if (!image || !originalImageUrl) return; if (!image || !originalImageUrl) return;
setIsEnhancing(true); setIsEnhancing(true);
try { try {
// 使用原图URL获取原图数据,而不是canvas的预览图 const imageUrl = await resolveProcessingImageUrl(originalImageUrl);
const base64Data = await imageUrlToBase64(originalImageUrl); const prompt = "画图标注-变清晰处理";
logger.debug("enhance_source_prepared", { base64Length: base64Data.length });
const result = await requestLongTaskResult({ const result = await requestLongTaskResult({
endpoint: "/api/enhance", endpoint: "/api/enhance",
payload: { payload: { imageUrl, prompt, includeBase64: false },
image_base64: base64Data, pollingParams: { sourceImageUrl: imageUrl, prompt, includeBase64: "false" },
prompt: "画图标注-变清晰处理",
},
pollingParams: {
prompt: "画图标注-变清晰处理",
},
}); });
if (result.success && result.image_base64) { const resultUrl = result?.original_url || result?.thumbnail_url;
// 保存处理后的图片URL和Base64(优先使用original_url,确保下载的是处理后的原图) if (!result?.success || !resultUrl) {
logger.info("enhance_completed", { throw new Error(result?.error || result?.detail || "变清晰处理失败");
hasOriginalUrl: !!result.original_url,
hasThumbnailUrl: !!result.thumbnail_url,
base64Length: result.image_base64?.length || 0,
});
// ✅ 验证:检查返回的URL是否是处理后的图片
if (result.original_url) {
// 验证URL格式(应该包含enhance-orig)
if (
!result.original_url.includes("enhance-orig") &&
!result.original_url.includes("enhance-orig")
) {
logger.warn("enhance_result_marker_missing");
}
setProcessedImageUrl(result.original_url);
} else if (result.thumbnail_url) {
logger.warn("enhance_original_url_missing", { hasThumbnailUrl: true });
setProcessedImageUrl(result.thumbnail_url);
} else {
logger.warn("enhance_image_url_missing");
setProcessedImageUrl(null);
}
setProcessedImageBase64(result.image_base64);
setProcessType("enhance");
toast.success(
`变清晰完成!图片已保存到相册。处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`
);
} else {
throw new Error(result.error || result.detail || "变清晰处理失败");
} }
setProcessedImageUrl(resultUrl);
setProcessedImageBase64(null);
setProcessType("enhance");
toast.success(
`变清晰完成!图片已保存到相册。处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`
);
} catch (error) { } catch (error) {
logger.error("enhance_failed", error); logger.error("enhance_failed", error);
toast.error( toast.error(
@ -1347,6 +1276,7 @@ export function ImageAnnotator({
}, },
body: JSON.stringify({ body: JSON.stringify({
image_base64: base64Data, image_base64: base64Data,
includeBase64: false,
prompt: `尺寸调整处理 - ${resizeCanvasWidth}x${resizeCanvasHeight}`, prompt: `尺寸调整处理 - ${resizeCanvasWidth}x${resizeCanvasHeight}`,
canvasWidth: resizeCanvasWidth, canvasWidth: resizeCanvasWidth,
canvasHeight: resizeCanvasHeight, canvasHeight: resizeCanvasHeight,

View File

@ -1884,6 +1884,7 @@ export function SceneFusionView({
imageUrl: item.image, imageUrl: item.image,
prompt: getModePrompt(mode), prompt: getModePrompt(mode),
skipGallerySave: false, skipGallerySave: false,
includeBase64: false,
}), }),
}); });
const payload = await response.json(); const payload = await response.json();
@ -1903,9 +1904,12 @@ export function SceneFusionView({
payload: { payload: {
imageUrl: item.image, imageUrl: item.image,
prompt: getModePrompt(mode), prompt: getModePrompt(mode),
includeBase64: false,
}, },
pollingParams: { pollingParams: {
prompt: getModePrompt(mode), prompt: getModePrompt(mode),
sourceImageUrl: item.image,
includeBase64: "false",
}, },
}); });
if (!payload?.success) { if (!payload?.success) {

View File

@ -204,6 +204,7 @@ export async function executeBoxCutoutJob(
userId: params.userId, userId: params.userId,
imageBuffer: croppedBuffer, imageBuffer: croppedBuffer,
imageBase64: croppedBuffer.toString("base64"), imageBase64: croppedBuffer.toString("base64"),
includeBase64: false,
sourceImageUrl: imageUrl, sourceImageUrl: imageUrl,
prompt: params.prompt || "框选抠图", prompt: params.prompt || "框选抠图",
chatId: params.chatId || null, chatId: params.chatId || null,

View File

@ -71,8 +71,8 @@ export async function processVideoCanvasImage(
const { executeRmbgJob } = await import("@/lib/ai/rmbg/service"); const { executeRmbgJob } = await import("@/lib/ai/rmbg/service");
const result = await executeRmbgJob({ const result = await executeRmbgJob({
userId: params.userId, userId: params.userId,
imageBuffer: await fetchImageBufferFromUrl(imageUrl),
inputImageUrl: imageUrl, inputImageUrl: imageUrl,
includeBase64: false,
sourceImageUrl: imageUrl, sourceImageUrl: imageUrl,
prompt: params.prompt, prompt: params.prompt,
}); });
@ -104,7 +104,8 @@ export async function processVideoCanvasImage(
if (definition.route === "enhance") { if (definition.route === "enhance") {
const result = await requestLongTaskResult({ const result = await requestLongTaskResult({
endpoint: resolveCanvasRuntimeEndpoint("/api/enhance", params.request.url), endpoint: resolveCanvasRuntimeEndpoint("/api/enhance", params.request.url),
payload: { imageUrl, scaleFactor: Number(args.scaleFactor) || 2 }, payload: { imageUrl, scaleFactor: Number(args.scaleFactor) || 2, includeBase64: false },
pollingParams: { sourceImageUrl: imageUrl, includeBase64: "false" },
headers: cookie ? { cookie } : undefined, headers: cookie ? { cookie } : undefined,
timeoutMs: 10 * 60_000, timeoutMs: 10 * 60_000,
}); });
@ -119,6 +120,7 @@ export async function processVideoCanvasImage(
headers: { "Content-Type": "application/json", ...(cookie ? { cookie } : {}) }, headers: { "Content-Type": "application/json", ...(cookie ? { cookie } : {}) },
body: JSON.stringify({ body: JSON.stringify({
image_url: imageUrl, image_url: imageUrl,
includeBase64: false,
horizontal_angle: Number(args.horizontalAngle) || 0, horizontal_angle: Number(args.horizontalAngle) || 0,
vertical_angle: Number(args.verticalAngle) || 0, vertical_angle: Number(args.verticalAngle) || 0,
zoom: Number(args.zoom) || 0, zoom: Number(args.zoom) || 0,

View File

@ -14,7 +14,6 @@ import {
} from "@/lib/ai/resize/service"; } from "@/lib/ai/resize/service";
import { import {
executeRmbgJob, executeRmbgJob,
fetchImageBufferFromUrl,
RmbgServiceError, RmbgServiceError,
} from "@/lib/ai/rmbg/service"; } from "@/lib/ai/rmbg/service";
import { generateCanvasImage } from "@/lib/canvas/generate-image"; import { generateCanvasImage } from "@/lib/canvas/generate-image";
@ -138,12 +137,14 @@ async function executeDirectAgentEnhanceJob(params: {
prompt: params.prompt, prompt: params.prompt,
chatId: params.chatId, chatId: params.chatId,
messageId: params.messageId, messageId: params.messageId,
includeBase64: false,
}, },
pollingParams: { pollingParams: {
prompt: params.prompt, prompt: params.prompt,
chatId: params.chatId, chatId: params.chatId,
messageId: params.messageId, messageId: params.messageId,
sourceImageUrl: params.imageUrl, sourceImageUrl: params.imageUrl,
includeBase64: "false",
}, },
timeoutMs: 10 * 60 * 1000, timeoutMs: 10 * 60 * 1000,
headers: cookieHeader headers: cookieHeader
@ -207,6 +208,7 @@ async function executeDirectAgentAngleEditJob(params: {
endpoint, endpoint,
payload: { payload: {
image_url: params.imageUrl, image_url: params.imageUrl,
includeBase64: false,
horizontal_angle: params.options.horizontalAngle, horizontal_angle: params.options.horizontalAngle,
vertical_angle: params.options.verticalAngle, vertical_angle: params.options.verticalAngle,
zoom: params.options.zoom, zoom: params.options.zoom,
@ -512,11 +514,10 @@ export async function executeDirectAgentImageEditTool(
} }
if (params.capability === "remove_background") { if (params.capability === "remove_background") {
const sourceBuffer = await fetchImageBufferFromUrl(params.sourceImageUrl);
const result = await executeRmbgJob({ const result = await executeRmbgJob({
userId: params.userId, userId: params.userId,
imageBuffer: sourceBuffer,
inputImageUrl: params.sourceImageUrl, inputImageUrl: params.sourceImageUrl,
includeBase64: false,
prompt: params.requestTextContent || "抠图处理", prompt: params.requestTextContent || "抠图处理",
chatId: params.chatId, chatId: params.chatId,
messageId: params.messageId, messageId: params.messageId,

View File

@ -302,6 +302,7 @@ async function executeForTarget(
requestHeaders: params.requestHeaders, requestHeaders: params.requestHeaders,
body: { body: {
image_url: target.sourceImageUrl, image_url: target.sourceImageUrl,
includeBase64: false,
horizontal_angle: asFiniteNumber(command.args.horizontalAngle) ?? 30, horizontal_angle: asFiniteNumber(command.args.horizontalAngle) ?? 30,
vertical_angle: asFiniteNumber(command.args.verticalAngle) ?? 0, vertical_angle: asFiniteNumber(command.args.verticalAngle) ?? 0,
zoom: asFiniteNumber(command.args.zoom) ?? 0, zoom: asFiniteNumber(command.args.zoom) ?? 0,

View File

@ -340,7 +340,7 @@ export async function executeAngleEditPOST(request: Request, trustedUserId: stri
success: true, success: true,
image_url: s3Result.original, image_url: s3Result.original,
thumbnail_url: s3Result.thumbnail, thumbnail_url: s3Result.thumbnail,
image_base64: imageBase64Result, image_base64: body.includeBase64 === false ? undefined : imageBase64Result,
processing_time: processingTime, processing_time: processingTime,
angles: { angles: {
horizontal_angle: finalHorizontalAngle, horizontal_angle: finalHorizontalAngle,

View File

@ -388,6 +388,7 @@ async function processWithVip98kEnhance(params: {
messageId: string | null; messageId: string | null;
sourceImageUrl: string | null; sourceImageUrl: string | null;
scaleFactor: number; scaleFactor: number;
includeBase64: boolean;
}) { }) {
const startedAt = Date.now(); const startedAt = Date.now();
const result = await executeConfiguredVip98kTask({ const result = await executeConfiguredVip98kTask({
@ -408,8 +409,7 @@ async function processWithVip98kEnhance(params: {
throw new Error(`VIP98K 变清晰结果下载失败(HTTP ${response.status})`); throw new Error(`VIP98K 变清晰结果下载失败(HTTP ${response.status})`);
} }
const outputBuffer = Buffer.from(await response.arrayBuffer()); const outputBuffer = Buffer.from(await response.arrayBuffer());
const outputBase64 = outputBuffer.toString("base64"); const uploaded = await uploadEnhanceImage(outputBuffer, "image/png");
const uploaded = await uploadEnhanceImage(outputBase64, "image/png");
const [savedImage] = await db const [savedImage] = await db
.insert(generatedImage) .insert(generatedImage)
.values({ .values({
@ -468,7 +468,7 @@ async function processWithVip98kEnhance(params: {
return { return {
success: true, success: true,
image_base64: outputBase64, image_base64: params.includeBase64 ? outputBuffer.toString("base64") : undefined,
thumbnail_url: uploaded.thumbnail, thumbnail_url: uploaded.thumbnail,
original_url: uploaded.original, original_url: uploaded.original,
processing_time: (Date.now() - startedAt) / 1000, processing_time: (Date.now() - startedAt) / 1000,
@ -634,6 +634,7 @@ async function executeFalEsrganFallback(params: {
messageId: string | null; messageId: string | null;
sourceImageUrl: string | null; sourceImageUrl: string | null;
requestedScaleFactor?: number; requestedScaleFactor?: number;
includeBase64: boolean;
reason: string; reason: string;
}) { }) {
const scaleFactor = params.requestedScaleFactor || 4; const scaleFactor = params.requestedScaleFactor || 4;
@ -651,6 +652,7 @@ async function executeFalEsrganFallback(params: {
prompt: params.prompt || "图片变清晰处理", prompt: params.prompt || "图片变清晰处理",
chatId: params.chatId, chatId: params.chatId,
messageId: params.messageId, messageId: params.messageId,
includeBase64: params.includeBase64,
sourceImageUrls: params.sourceImageUrl sourceImageUrls: params.sourceImageUrl
? [params.sourceImageUrl] ? [params.sourceImageUrl]
: undefined, : undefined,
@ -914,6 +916,7 @@ export async function executeEnhancePOST(request: Request, trustedUserId: string
messageId, messageId,
sourceImageUrl, sourceImageUrl,
scaleFactor, scaleFactor,
includeBase64,
}); });
return NextResponse.json(payload); return NextResponse.json(payload);
} catch (error) { } catch (error) {
@ -1056,7 +1059,7 @@ export async function executeEnhancePOST(request: Request, trustedUserId: string
console.log(`[Enhance-RealESRGAN] ✅ 全部完成,总耗时: ${result.processingTime.toFixed(2)}秒`); console.log(`[Enhance-RealESRGAN] ✅ 全部完成,总耗时: ${result.processingTime.toFixed(2)}秒`);
return NextResponse.json({ return NextResponse.json({
success: true, success: true,
image_base64: result.imageBase64, image_base64: includeBase64 ? result.imageBase64 : undefined,
thumbnail_url: thumbnailUrl, thumbnail_url: thumbnailUrl,
original_url: originalUrl, original_url: originalUrl,
processing_time: result.processingTime, processing_time: result.processingTime,
@ -1074,6 +1077,7 @@ export async function executeEnhancePOST(request: Request, trustedUserId: string
messageId, messageId,
sourceImageUrl, sourceImageUrl,
requestedScaleFactor, requestedScaleFactor,
includeBase64,
reason: error instanceof Error ? error.message : "RealESRGAN 备用服务失败", reason: error instanceof Error ? error.message : "RealESRGAN 备用服务失败",
}); });
return NextResponse.json(fallbackPayload); return NextResponse.json(fallbackPayload);
@ -1254,6 +1258,7 @@ export async function executeEnhancePOST(request: Request, trustedUserId: string
messageId, messageId,
sourceImageUrl, sourceImageUrl,
requestedScaleFactor, requestedScaleFactor,
includeBase64,
reason: fetchError instanceof Error ? fetchError.message : "AOS 高清任务创建失败", reason: fetchError instanceof Error ? fetchError.message : "AOS 高清任务创建失败",
}); });
return NextResponse.json(fallbackPayload); return NextResponse.json(fallbackPayload);

View File

@ -18,7 +18,7 @@ export async function preprocessProductImageWithRmbg(params: {
const response = await executeRemoveBackgroundPOST(new Request(new URL("/api/rmbg", request.url), { const response = await executeRemoveBackgroundPOST(new Request(new URL("/api/rmbg", request.url), {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json", "X-Request-ID": `${requestId}:pre-rmbg` }, headers: { "Content-Type": "application/json", "X-Request-ID": `${requestId}:pre-rmbg` },
body: JSON.stringify({ imageUrl: productImageUrl, prompt: "场景裂变预处理-抠图", skipGallerySave: true }), body: JSON.stringify({ imageUrl: productImageUrl, prompt: "场景裂变预处理-抠图", skipGallerySave: true, includeBase64: false }),
}), userId); }), userId);
const payload = await response.json(); const payload = await response.json();
if (!response.ok) { if (!response.ok) {

View File

@ -61,6 +61,7 @@ export async function executeImageOperation(
: input.operation === "angle-edit" : input.operation === "angle-edit"
? { ? {
image_url: input.imageUrl, image_url: input.imageUrl,
includeBase64: false,
horizontal_angle: input.horizontalAngle, horizontal_angle: input.horizontalAngle,
vertical_angle: input.verticalAngle, vertical_angle: input.verticalAngle,
zoom: input.zoom, zoom: input.zoom,

View File

@ -704,7 +704,7 @@ export const imageGenerationService = {
const response = await fetch('/api/rmbg', { const response = await fetch('/api/rmbg', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ imageUrl }), // 使用 imageUrl 参数 body: JSON.stringify({ imageUrl, includeBase64: false }),
}); });
const data = await response.json(); const data = await response.json();
if (data.success && data.original_url) { if (data.success && data.original_url) {
@ -780,22 +780,22 @@ export const imageGenerationService = {
} }
): Promise<ApiResponse<{ url: string }>> { ): Promise<ApiResponse<{ url: string }>> {
try { try {
const response = await fetch('/api/enhance', { const data = await requestLongTaskResult({
method: 'POST', endpoint: '/api/enhance',
headers: { 'Content-Type': 'application/json' }, payload: {
body: JSON.stringify({
imageUrl, imageUrl,
scaleFactor: options?.scaleFactor, scaleFactor: options?.scaleFactor,
}), includeBase64: false,
},
pollingParams: { sourceImageUrl: imageUrl, includeBase64: 'false' },
}); });
const data = await response.json(); if (data?.success && data.original_url) {
if (data.success && data.original_url) {
return { success: true, data: { url: data.original_url } }; return { success: true, data: { url: data.original_url } };
} }
return { success: false, error: data.error || '图片增强失败' }; return { success: false, error: data?.error || data?.detail || '图片增强失败' };
} catch (error) { } catch (error) {
logCatch(error, "enhance_image"); logCatch(error, "enhance_image");
return { success: false, error: '图片增强失败' }; return { success: false, error: error instanceof Error ? error.message : '图片增强失败' };
} }
}, },
@ -992,6 +992,7 @@ export const imageGenerationService = {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
image_base64: base64, image_base64: base64,
includeBase64: false,
canvasWidth: width, canvasWidth: width,
canvasHeight: height, canvasHeight: height,
prompt: '尺寸调整', prompt: '尺寸调整',
@ -1033,6 +1034,7 @@ export const imageGenerationService = {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
image_url: params.imageUrl, image_url: params.imageUrl,
includeBase64: false,
horizontal_angle: params.horizontalAngle, horizontal_angle: params.horizontalAngle,
vertical_angle: params.verticalAngle, vertical_angle: params.verticalAngle,
zoom: params.zoom, zoom: params.zoom,

View File

@ -93,3 +93,22 @@ test("canvas cutout keeps the archived PNG as the original and skips production
expect(result.image_base64).toBeUndefined(); expect(result.image_base64).toBeUndefined();
expect(calls).toEqual([`${input}?imageInfo`, endpoint, `${endpoint}/test-aos-task`, "aos-rmbg-test-aos-task"]); expect(calls).toEqual([`${input}?imageInfo`, endpoint, `${endpoint}/test-aos-task`, "aos-rmbg-test-aos-task"]);
}); });
test("a batch enhancement completed on submission returns only stored image links", async () => {
const { load, calls, endpoint } = testImageTransfer("scale");
const enhance = load("lib/canvas/operations/enhance.ts");
const response = await enhance.executeEnhancePOST(
new Request("https://app.example/enhance", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ imageUrl: input, scaleFactor: 2, includeBase64: false }),
}),
"test-user",
);
expect(response.status).toBe(200);
const result = await response.json();
expect(result.original_url).toBe(archived);
expect(result.thumbnail_url).toBeTruthy();
expect(result).not.toHaveProperty("image_base64");
expect(calls).toEqual([`${input}?imageInfo`, endpoint, `${endpoint}/test-aos-task`, "aos-enhance-test-aos-task"]);
});

View File

@ -356,6 +356,7 @@ test("angle operation sends normalized numeric fields and accepts the dedicated
const handler = async (req: Request) => { const handler = async (req: Request) => {
expect(await req.json()).toEqual({ expect(await req.json()).toEqual({
image_url: "https://example.com/source.png", image_url: "https://example.com/source.png",
includeBase64: false,
horizontal_angle: 180, horizontal_angle: 180,
vertical_angle: 45, vertical_angle: 45,
zoom: 5, zoom: 5,