Resizing images in C#

一个人想着一个人 提交于 2019-12-06 15:01:04

The code is just inappropriate. It doesn't score points for using floating point math, that has a knack for rounding the wrong way so you can easily end up with 99 pixels instead of 100. Always favor integer math so you can control the rounding. And it just doesn't do anything to ensure that one of the dimensions is large enough, the way to end up with 96 pixels. Just write better code. Like:

    public static Image ResizeImage(Image img, int minsize) {
        var size = img.Size;
        if (size.Width >= size.Height) {
            // Could be: if (size.Height < minsize) size.Height = minsize;
            size.Height = minsize;
            size.Width = (size.Height * img.Width + img.Height - 1) / img.Height;
        }
        else {
            size.Width = minsize;
            size.Height = (size.Width * img.Height + img.Width - 1) / img.Width;
        }
        return new Bitmap(img, size);
    }

I left a comment to show what you do if you are only want to make sure the image is large enough and accept larger images. It wasn't clear from the question. If that's the case then replicate that if statement in the else clause as well.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!