algorithm - 图像调整算法

标签 algorithm image resize

我想编写一个函数来缩小图像以适应指定的边界。例如,我想调整 2000x2333 图像的大小以适应 1280x800。必须保持纵横比。我提出了以下算法:

NSSize mysize = [self pixelSize]; // just to get the size of the original image
int neww, newh = 0;
float thumbratio = width / height; // width and height are maximum thumbnail's bounds
float imgratio = mysize.width / mysize.height;

if (imgratio > thumbratio)
{
    float scale = mysize.width / width;
    newh = round(mysize.height / scale);
    neww = width;
}
else
{
    float scale = mysize.height / height;
    neww = round(mysize.width / scale);
    newh = height;
}

它似乎奏效了。好吧……似乎。但是后来我尝试将 1280x1024 图像的大小调整为 1280x800 的边界,它给了我 1280x1024 的结果(这显然不适合 1280x800)。

有人知道这个算法应该如何工作吗?

最佳答案

我通常的做法是看原来的宽度和新的宽度的比例,以及原来的高度和新的高度的比例。

在此之后按最大比例缩小图像。例如,如果您想将 800x600 的图像调整为 400x400 的图像,则宽度比为 2,高度比为 1.5。将图像缩小 2 倍,得到 400x300 的图像。

NSSize mysize = [self pixelSize]; // just to get the size of the original image
int neww, newh = 0;
float rw = mysize.width / width; // width and height are maximum thumbnail's bounds
float rh = mysize.height / height;

if (rw > rh)
{
    newh = round(mysize.height / rw);
    neww = width;
}
else
{
    neww = round(mysize.width / rh);
    newh = height;
}

关于algorithm - 图像调整算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3332237/

相关文章:

python - 为什么将 DO 添加到我的递归中会使其停止正常工作?

java - Pollard Rho 找不到因子

ios - Assets 目录在 Xcode 10.3 中返回 nil 图像,在 10.1 中工作正常

Android高分辨率图像处理

jquery-ui - jQuery UI 可调整大小在调整大小事件中停止调整大小

c# - 从不同列表中获取优先(按受欢迎程度)列表

java - 图片图标不起作用?

javascript - 使用 jQuery resizing 调整大小结束后获取宽度

javascript - 调整使用 window.open 创建的窗口大小

algorithm - 节点连接情况的良好类设计是什么?