在JavaScript中计算图像比例。结果可以近似于规格
Calculate image ratio in JavaScript. Result can be approximate to the specification
我想知道大概的图片比例。
规格为16/9和3/1;
我要检查的示例图像的尺寸为 1281x720 像素;
要计算比率,我使用此代码:
const gcd = (a, b) => b ? gcd(b, a % b): a;
const aspectRatio = (width, height) => {
const divisor = gcd(width, height);
return `${width / divisor}:${height / divisor}`;
};
这段代码工作正常。
嗯,有没有可能检查图片是接近 16/9 还是接近 3/1?
一个大概的指示对我来说就足够了
也许是这样的?
const aspectRatio = (width, height) => {
const ratio = (width/height)-(16/9) < 0.1
? '16:9'
: ((width/height)-(3/1) < 0.1 ? '3:1' : 'out of spec');
return `${ratio}`;
};
console.log(aspectRatio(1281, 720));
console.log(aspectRatio(606, 202));
console.log(aspectRatio(320, 100));
请注意,我现在选择的 "tolerance" 是任意的 10%,图像尺寸越大,它变得越不准确(因为 10% 将是一个更大的像素偏差范围),所以你可能想要考虑根据自己的喜好降低它...上面的代码绝对不优雅 =),但对于您的特定场景,它应该可以工作。
更 "elegant" 和更灵活的解决方案是对您的函数进行稍微扩展的版本,如下所示:
const aspectRatio = (width, height, tolerance = 0.1, specs = ['16:9', '3:1']) => {
return specs.filter((spec) => {
if ( Math.abs((width/height)-eval(spec.replace(':', '/'))) <= tolerance ) {
return spec;
}
})[0] || false;
};
console.log(aspectRatio(1281, 720));
console.log(aspectRatio(606, 202));
console.log(aspectRatio(320, 100));
这将允许指定
- a) 图像尺寸可以偏离 "perferct ratio"
的容差级别
- b) 允许的图像 ratio-specifications
这是一个正确的比例,因此您可以检查您的 width/height 是否更接近 16/9 或 3/1:
const width = 1281
const height = 720
const distanceFrom16by9 = Math.abs(1281/720 - 16/9)
const distanceFrom3by1 = Math.abs(1281/720 - 3)
const ratio = distanceFrom16by9 < distanceFrom3by1 ? "16:9" : "3:1"
console.log(ratio)
我想知道大概的图片比例。 规格为16/9和3/1;
我要检查的示例图像的尺寸为 1281x720 像素;
要计算比率,我使用此代码:
const gcd = (a, b) => b ? gcd(b, a % b): a;
const aspectRatio = (width, height) => {
const divisor = gcd(width, height);
return `${width / divisor}:${height / divisor}`;
};
这段代码工作正常。
嗯,有没有可能检查图片是接近 16/9 还是接近 3/1? 一个大概的指示对我来说就足够了
也许是这样的?
const aspectRatio = (width, height) => {
const ratio = (width/height)-(16/9) < 0.1
? '16:9'
: ((width/height)-(3/1) < 0.1 ? '3:1' : 'out of spec');
return `${ratio}`;
};
console.log(aspectRatio(1281, 720));
console.log(aspectRatio(606, 202));
console.log(aspectRatio(320, 100));
请注意,我现在选择的 "tolerance" 是任意的 10%,图像尺寸越大,它变得越不准确(因为 10% 将是一个更大的像素偏差范围),所以你可能想要考虑根据自己的喜好降低它...上面的代码绝对不优雅 =),但对于您的特定场景,它应该可以工作。
更 "elegant" 和更灵活的解决方案是对您的函数进行稍微扩展的版本,如下所示:
const aspectRatio = (width, height, tolerance = 0.1, specs = ['16:9', '3:1']) => {
return specs.filter((spec) => {
if ( Math.abs((width/height)-eval(spec.replace(':', '/'))) <= tolerance ) {
return spec;
}
})[0] || false;
};
console.log(aspectRatio(1281, 720));
console.log(aspectRatio(606, 202));
console.log(aspectRatio(320, 100));
这将允许指定
- a) 图像尺寸可以偏离 "perferct ratio" 的容差级别
- b) 允许的图像 ratio-specifications
这是一个正确的比例,因此您可以检查您的 width/height 是否更接近 16/9 或 3/1:
const width = 1281
const height = 720
const distanceFrom16by9 = Math.abs(1281/720 - 16/9)
const distanceFrom3by1 = Math.abs(1281/720 - 3)
const ratio = distanceFrom16by9 < distanceFrom3by1 ? "16:9" : "3:1"
console.log(ratio)