按比例调整图像大小的算法,使其尽可能接近给定尺寸

Algorithm to resize an image proportionally keeping it as close as possible to given dimensions

本文关键字:接近 尽可能 图像 调整 算法 按比例      更新时间:2023-09-26

示例

myFunction(400, 300, 50, 100) => 必须返回宽度和高度才能按比例调整我的 400x300(第一个和第二个参数)图像的大小。调整大小的图像必须至少为 50x100(第 3 和第 4 个参数)。去 52x 是完全可以的。或。。x102 但"超大尺寸"必须在材料上尽可能小,以保持纵横比。

我必须编写一个函数(我将使用Javascript/Jquery,但我们不必担心语言:我对逻辑感兴趣),如下所示:

[new_image_width, new_image_height] function(image_width, image_height, reference_width, reference_height)

此函数采用:

  • image_width:图像的宽度
  • image_height:图像的高度
  • reference_width:图像的最小宽度(见下文)
  • reference_height:图像的最小高度(见下文)

它返回:

  • new_image_width:按比例调整图像大小的宽度(见下文)
  • new_image_height:按比例调整图像大小的高度(见下文)

该函数必须计算最接近相应"参考"参数的宽度和高度,而不是低于并保留纵横比

我的函数不能实际调整图像大小,只返回要调整大小的新整数。

注意:我对代码很满意,但在数学方面是一年级水平。请表现出一些怜悯:-(

如果你不关心舍入误差

ratio = min(image_width / reference_width, image_height / reference_height)

并返回

image_width / ratio
image_height / ratio

如果您确实关心舍入误差

找到image_widthimage_height的最大公约数GCD。您可以用完全相同的纵横比制作的最小图像具有尺寸

image_width' = image_width / GCD
image_height' = image_height / GCD

每个具有完全相同纵横比的较大图像都是这些图像的整数倍。所以,让

ratio_width = ceil(reference_width / image_width')
ratio_height = ceil(reference_heigth / image_heigth')

ratio = max(ratio_width, ratio_height)

那么你的结果是

ratio * image_width'
ratio * image_height'

好的,所以试试这个:

function myFunction(image_width, image_height, reference_width, reference_height) {
    var proportion = image_width/image_height;
    if(reference_height*proportion < reference_width){
        return [reference_width, reference_width/proportion];
    } else {
        return [reference_height*proportion,reference_height];
    }
}