algorithm - 按像素数量调整图像大小

标签 algorithm

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

一张图片,例如 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

在实现时,请记住对涉及ratioscale 的所有计算使用 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/

相关文章:

java - 计算 n 个元素上所有可能根的高度为 h 的二叉搜索树的数量

algorithm - 通过适应度函数从种群中选择个体

performance - 使用计数器是一种好习惯吗?

algorithm - 这两种算法都是 LZSS 的有效实现吗?

algorithm - 将 Google map 上的一组点平均为一个较小的集合

php - php if 代码背后的逻辑

生成所有可能的 N 位数字的算法,其数字按递增顺序排列

java - 查找按字符索引分组的多个字符串并集的算法

c++ - Relation和大多数Merge Operation的计算?

c# - 检查日期是否在跨度重复之间的最有效方法是什么?