我试图找出答案,但我做不到。
一张图片,例如 241x76
共有 18,316 像素 (241 * 76)
。
调整大小规则是,像素数量不能超过10,000
。
那么,我怎样才能获得保持纵横比并小于 10,000
像素的新尺寸?
最佳答案
伪代码:
pixels = width * height
if (pixels > 10000) then
ratio = width / height
scale = sqrt(pixels / 10000)
height2 = floor(height / scale)
width2 = floor(ratio * height / scale)
ASSERT width2 * height2 <= 10000
end if
在实现时,请记住对涉及ratio
和scale
的所有计算使用 float 学。
python
import math
def capDimensions(width, height, maxPixels=10000):
pixels = width * height
if (pixels <= maxPixels):
return (width, height)
ratio = float(width) / height
scale = math.sqrt(float(pixels) / maxPixels)
height2 = int(float(height) / scale)
width2 = int(ratio * height / scale)
return (width2, height2)
关于algorithm - 按像素数量调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10106792/