fix: 优化阿里生图分辨率计算,确保宽高比和分辨率正确配合
- 改进 clamp 逻辑:超出范围时按比例缩放而非直接截断 - 确保在缩放后仍保持正确的宽高比 - 分辨率等级(1K/2K/4K)和宽高比(4:3/16:9等)可以正确组合
This commit is contained in:
parent
086fb70eb2
commit
f46ee10eba
@ -399,20 +399,45 @@ export function createAlibabaImage({ apiKey, baseURL }: AlibabaImageConfig) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const [w, h] = ratioMap[ratio] || [1, 1];
|
const [w, h] = ratioMap[ratio] || [1, 1];
|
||||||
|
const aspectValue = w / h;
|
||||||
|
|
||||||
// 计算宽高,保持总像素接近 base*base
|
// 计算宽高,保持总像素接近 base*base
|
||||||
const totalPixels = base * base;
|
const totalPixels = base * base;
|
||||||
const aspectValue = w / h;
|
|
||||||
|
|
||||||
// height = sqrt(totalPixels / aspectValue)
|
// height = sqrt(totalPixels / aspectValue)
|
||||||
// width = height * aspectValue
|
// width = height * aspectValue
|
||||||
let height = Math.round(Math.sqrt(totalPixels / aspectValue));
|
let height = Math.round(Math.sqrt(totalPixels / aspectValue));
|
||||||
let width = Math.round(height * aspectValue);
|
let width = Math.round(height * aspectValue);
|
||||||
|
|
||||||
// 确保宽高在 512-2048 范围内
|
// 阿里云 API 限制:宽高在 512-2048 之间
|
||||||
const clamp = (val: number) => Math.max(512, Math.min(2048, val));
|
const MIN_SIZE = 512;
|
||||||
width = clamp(width);
|
const MAX_SIZE = 2048;
|
||||||
height = clamp(height);
|
|
||||||
|
// 如果超出范围,按比例缩放,同时保持宽高比
|
||||||
|
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;
|
width = Math.round(width / 2) * 2;
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user