使用Graphics.FromImage.DrawImage缩小图像的低视觉质量

时间:2015-09-16 13:08:19

标签: c# image-resizing

关注此问题Resize image proportionally with MaxHeight and MaxWidth constraints

我按如下方式实施了解决方案:

public static class ImageResizer
{
    public static Image ResizeImage(String origFileLocation, int maxWidth, int maxHeight)
    {
        Image img = Image.FromFile(origFileLocation);

        if (img.Height < maxHeight && img.Width < maxWidth) return img;
        using (img)
        {
            Double xRatio = (double)maxWidth / img.Width;
            Double yRatio = (double)maxHeight / img.Height;
            Double ratio = Math.Max(xRatio, yRatio);

            int nnx = (int)Math.Floor(img.Width * ratio);
            int nny = (int)Math.Floor(img.Height * ratio);

            Bitmap cpy = new Bitmap(nnx, nny, PixelFormat.Format32bppArgb);
            using (Graphics gr = Graphics.FromImage(cpy))
            {
                gr.Clear(Color.Transparent);

                // This is said to give best quality when resizing images
                gr.SmoothingMode = SmoothingMode.HighQuality;
                gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;

                gr.DrawImage(img,
                    new Rectangle(0, 0, nnx, nny),
                    new Rectangle(0, 0, img.Width, img.Height),
                    GraphicsUnit.Pixel);
            }
            return cpy;
        }
    }

}

然后以这种方式保存图像:

                resized.Save(resizedFilePath, System.Drawing.Imaging.ImageFormat.Gif);

然而,尝试它,缩小图像,结果非常粗糙,你可以在这张照片中看到 enter image description here

我认为缩小的图像应该没有明显的效果。关于它的任何想法?

2 个答案:

答案 0 :(得分:0)

是。正如@Ivan Stoev建议的那样。问题不在于调整大小,而是在保存方法中出于某种原因默认压缩图像。

我用过

resized.Save(resizedFilePath, System.Drawing.Imaging.ImageFormat.Png);

用于保存,现在一切似乎都很好。谢谢。

答案 1 :(得分:-2)

  

resized.Save(resizedFilePath,System.Drawing.Imaging.ImageFormat.Png);

尺寸大而不是优化