c# - 调整图像大小时出现质量问题?

标签 c# image

我正在使用此代码调整图像大小。但结果并不好,我想要最好的质量。我知道它的质量很差,因为我也用 photoshop 调整了相同图像的大小,结果却不同得更好。我该如何解决?

private static Image resizeImage(Image imgToResize, Size size)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)size.Width / (float)sourceWidth);
        nPercentH = ((float)size.Height / (float)sourceHeight);

        if (nPercentH < nPercentW)
            nPercent = nPercentH;
        else
            nPercent = nPercentW;

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap b = new Bitmap(destWidth, destHeight);
        Graphics g = Graphics.FromImage((Image)b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();

        return (Image)b;
    }

最佳答案

这是我使用的例程。也许你会发现它很有用。这是一种扩展方法,可以引导。唯一的区别是我省略了保留纵横比的代码,您可以轻松插入。

public static Image GetImageHiQualityResized(this Image image, int width, int height)
{
    var thumb = new Bitmap(width, height);
    using (var g = Graphics.FromImage(thumb))
    {
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.InterpolationMode = InterpolationMode.High;
        g.DrawImage(image, new Rectangle(0, 0, thumb.Width, thumb.Height));
        return thumb;
    }
}

此扩展方法的示例用法包括:

// Load the original image
using(var original = Image.FromFile(@"C:\myimage.jpg"))
using(var thumb = image.GetImageHiQualityResized(120, 80))
{
    thumb.Save(@"C:\mythumb.png", ImageFormat.Png);
}

注释

默认的 JPG 编码和默认的 PNG 编码之间的区别确实非常不同。下面是使用您的示例的两个缩略图,一个用 ImageFormat.Png 保存,一个用 ImageFormat.Jpeg 保存。

PNG 图片

PNG Image

JPEG 图片

JPEG Image

如果您确定您绝对必须使用 JPEG,您可能会发现原始发帖人在这个问题中所做的工作很有帮助。它涉及将图像编解码器和编码参数配置为高质量设置。 .NET Saving jpeg with the same quality as it was loaded

如果是我,我会尽快使用 PNG 格式,因为它是无损的。

关于c# - 调整图像大小时出现质量问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3584328/

相关文章:

android - 适用于 Android 的 Titanium/Appcelerator : Multiple density images not found

c# - 我在 executenonquery mysql.dll 期间遇到 fatal error ,空文件路径不合法

swift - 关于线程 1 : Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

java - ZeroMQ:消失的消息

c# - 如何持久化实现状态模式的对象?

c# - 让 Windows Mobile 6 手机保持活力

javascript - 在 C# 中反序列化 javascript 对象数组的问题

python - 在 python 中升级 SVG 图像而不损失其质量

CSS-多背景图像

c# - Wpf 数据虚拟化