使用rmagick/imagemagick调整图像大小,使其小于宽度和高度的指定乘积



我正在运行一个调整过大图像大小的脚本。我曾使用"resize_to_fit"将图像缩小到特定的像素大小,具体取决于较长的一侧,但我想知道是否可以使用此逻辑:对于宽度x高度乘积大于设定值的任何图像,调整图像大小,使新的宽度和高度值尽可能大,同时仍低于该值。换言之,我不想随意调整尺寸,我希望在这个转换中保持纵横比。这可能更像是一个数学问题,而不是一个红宝石问题,但无论如何,这就是我尝试过的:

image = Magick::Image.read(image_file)[0];
dimensions = image.columns, image.rows
resolution = dimensions[0] * dimensions[1]
if resolution > 4000000
resolution_ratio = 4000000 / resolution.to_f
dimension_ratio = dimensions[0].to_f * resolution_ratio
img = img.resize_to_fit(dimension_ratio,dimension_ratio)
img.write("#{image}")
end

假设图像的宽度为2793px,高度为1970px。决议为5502210。因此,它通过条件语句,截至目前,输出新的宽度2030,高度1432。这两者的乘积是2906960,显然远低于4000000。但是,还有其他可能的宽x高组合,其产品可能比2906960更接近4000000像素。有没有办法确定这些信息,然后相应地调整其大小?

您需要正确计算ratio,它是所需维度除以(row乘以col)的平方根:

row, col = [2793, 1970]
ratio = Math.sqrt(4_000_000.0 / (row * col))
[row, col].map &ratio.method(:*)
#⇒ [
#  [0] 2381.400006266842,
#  [1] 1679.6842149465374
#]
[row, col].map(&ratio.method(:*)).reduce(:*)
#∞ 3999999.9999999995

最新更新