【问题标题】:Image resizing algorithm图像大小调整算法
【发布时间】:2011-03-20 22:06:57
【问题描述】:

我想编写一个函数来缩小图像以适应指定的范围。例如,我想调整 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)。

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

【问题讨论】:

    标签: algorithm image resize


    【解决方案1】:

    我通常这样做的方法是查看原始宽度与新宽度之间的比率以及原始高度与新高度之间的比率。

    在此之后以最大比例缩小图像。例如,如果您想将 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;
    }
    

    【讨论】:

    • 哦,我应该为您添加 1280x1024 到 1280x800 的示例,比例为 1 和 1.28,调整大小后为 1000 x 800
    【解决方案2】:

    这是解决问题的一种方法:

    您知道图像的高度或宽度将等于边界框的高度或宽度。

    一旦您确定了哪个维度等于边界框的维度,您就可以使用图像的纵横比来计算另一个维度。

    double sourceRatio = sourceImage.Width / sourceImage.Height;
    double targetRatio = targetRect.Width / targetRect.Height;
    
    Size finalSize;
    if (sourceRatio > targetRatio)
    {
        finalSize = new Size(targetRect.Width, targetRect.Width / sourceRatio);
    }
    else
    {
        finalSize = new Size(targetRect.Height * sourceRatio, targetRect.Height);
    }
    

    【讨论】:

    • 什么是 imageRatio?
    • @JonathanAquino 我认为应该是sourceRatio。好皮卡。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多