fix: 修复阿里生图模型 aspectRatio 参数不生效问题
Some checks failed
Lint / build (20) (push) Has been cancelled
Playwright Tests / test (push) Has been cancelled

- 将 aspectRatio(如 4:3)转换为阿里云 API 需要的 size 格式(如 1365*1024)
- 结合 imageSize(1K/2K/4K)确定基准分辨率
- 自动计算保持总像素数接近目标分辨率的宽高
- 确保宽高在阿里云 API 要求的 512-2048 范围内
This commit is contained in:
Your Name 2026-01-18 11:16:24 +08:00
parent 68abf3e3fa
commit 086fb70eb2

View File

@ -368,19 +368,69 @@ export function createAlibabaImage({ apiKey, baseURL }: AlibabaImageConfig) {
seed: options.imageParams?.seed,
};
// 处理分辨率
// 处理分辨率:结合 aspectRatio(宽高比)和 imageSize(分辨率等级)
const aspectRatio = options.imageParams?.aspectRatio || "auto";
const imageSize = options.imageParams?.imageSize || "2K";
// 根据分辨率等级确定基准像素
const baseSizeMap: Record<string, number> = {
"1K": 1024,
"2K": 1536,
"4K": 2048,
};
const baseSize = baseSizeMap[imageSize] || 1536;
// 根据宽高比计算实际分辨率
// 阿里云 API 要求宽高在 512-2048 之间
const calculateSize = (ratio: string, base: number): string => {
// 解析宽高比
const ratioMap: Record<string, [number, number]> = {
"auto": [1, 1],
"1:1": [1, 1],
"16:9": [16, 9],
"9:16": [9, 16],
"4:3": [4, 3],
"3:4": [3, 4],
"3:2": [3, 2],
"2:3": [2, 3],
"5:4": [5, 4],
"4:5": [4, 5],
"21:9": [21, 9],
};
const [w, h] = ratioMap[ratio] || [1, 1];
// 计算宽高,保持总像素接近 base*base
const totalPixels = base * base;
const aspectValue = w / h;
// height = sqrt(totalPixels / aspectValue)
// width = height * aspectValue
let height = Math.round(Math.sqrt(totalPixels / aspectValue));
let width = Math.round(height * aspectValue);
// 确保宽高在 512-2048 范围内
const clamp = (val: number) => Math.max(512, Math.min(2048, val));
width = clamp(width);
height = clamp(height);
// 确保是偶数(某些图像处理可能需要)
width = Math.round(width / 2) * 2;
height = Math.round(height / 2) * 2;
return `${width}*${height}`;
};
// 如果用户直接指定了 size,使用用户指定的
if (options.imageParams?.size) {
params.size = options.imageParams.size;
} else if (options.imageParams?.imageSize) {
// 从 imageSize (如 "2K") 转换为具体分辨率
const sizeMap: Record<string, string> = {
"1K": "1024*1024",
"2K": "1536*1536",
"4K": "2048*2048",
};
params.size = sizeMap[options.imageParams.imageSize] || "1024*1024";
} else {
// 否则根据 aspectRatio 和 imageSize 计算
params.size = calculateSize(aspectRatio, baseSize);
}
console.log(`[Alibaba Image] Calculated size: aspectRatio=${aspectRatio}, imageSize=${imageSize} => size=${params.size}`);
// 根据图片数量确定编辑模式
const editMode = imageUrls.length === 1 ? "单图编辑" : `多图融合 (${imageUrls.length}张)`;
console.log("[Alibaba Image] 编辑模式:", editMode);