调整代码大小的质量?

时间:2017-07-06 05:27:34

标签: c# image

所以我试图调整巨大的图像,例如5500x3500 JPG,低至1024x768或更低。以下功能有效,但它确实运行了质量,使文本全部模糊。

static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);
    Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
    Bitmap bmp = new Bitmap(newImage);

    return bmp;
}

想知道更好的方法吗?

2 个答案:

答案 0 :(得分:0)

正如评论中所建议的那样,您应该使用插值模式来控制缩放期间的图像质量。要了解如何使用它,请参阅Microsoft的以下文档,

https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-use-interpolation-mode-to-control-image-quality-during-scaling

答案 1 :(得分:0)

您应该将Graphics-object中的质量属性设置为HighQuality:

static public Bitmap ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    using (Bitmap newImage = new Bitmap(newWidth, newHeight))
    {
        using (Graphics g = Graphics.FromImage(newImage))
        {
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

            Bitmap bmp = new Bitmap(newImage);
            return bmp;
        }
    } 
}

另外一定要使用带有实现iDisposable的对象的using-block:ImageBitmapGraphichs