按像素数量调整图像大小

Rat*_*ata 1 algorithm

我试图找出答案,但我做不到.

例如,图像241x76总共有18,316 pixels (241 * 76).调整大小规则是,像素数量无法通过10,000.那么,我怎样才能让新尺寸保持纵横比并且小于10,000像素?

Dee*_*tan 5

伪代码:

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
Run Code Online (Sandbox Code Playgroud)

请记住对所有涉及ratioscale实现的计算使用浮点数学.


蟒蛇

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)
Run Code Online (Sandbox Code Playgroud)