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

low visual quality of shrinked image using Graphics.FromImage.DrawImage

关注这个问题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);

但是,尝试一下,缩小图像,结果非常粗糙,正如您在这张照片中看到的那样

我认为缩小图像应该不会产生明显的影响。有什么想法吗?

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

我用过

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

为了保存,现在一切似乎都很好。谢谢。

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

尺码偏大未优化