diff --git a/lib/ai/providers/alibaba-image.ts b/lib/ai/providers/alibaba-image.ts index eb4fc3b35..a59904d3a 100644 --- a/lib/ai/providers/alibaba-image.ts +++ b/lib/ai/providers/alibaba-image.ts @@ -399,20 +399,45 @@ export function createAlibabaImage({ apiKey, baseURL }: AlibabaImageConfig) { }; const [w, h] = ratioMap[ratio] || [1, 1]; + const aspectValue = w / h; // 计算宽高,保持总像素接近 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); + // 阿里云 API 限制:宽高在 512-2048 之间 + const MIN_SIZE = 512; + const MAX_SIZE = 2048; + + // 如果超出范围,按比例缩放,同时保持宽高比 + if (width > MAX_SIZE) { + const scale = MAX_SIZE / width; + width = MAX_SIZE; + height = Math.round(height * scale); + } + if (height > MAX_SIZE) { + const scale = MAX_SIZE / height; + height = MAX_SIZE; + width = Math.round(width * scale); + } + if (width < MIN_SIZE) { + const scale = MIN_SIZE / width; + width = MIN_SIZE; + height = Math.round(height * scale); + } + if (height < MIN_SIZE) { + const scale = MIN_SIZE / height; + height = MIN_SIZE; + width = Math.round(width * scale); + } + + // 最终 clamp 确保在范围内 + width = Math.max(MIN_SIZE, Math.min(MAX_SIZE, width)); + height = Math.max(MIN_SIZE, Math.min(MAX_SIZE, height)); // 确保是偶数(某些图像处理可能需要) width = Math.round(width / 2) * 2;