我正在使用此代码调整图像大小。但结果并不好,我想要最好的质量。我知道它的质量很差,因为我也用 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);
}
注释
- 参见 http://msdn.microsoft.com/en-us/library/84767bxk.aspx了解保存和加载图像的其他方法。
默认的 JPG 编码和默认的 PNG 编码之间的区别确实非常不同。下面是使用您的示例的两个缩略图,一个用 ImageFormat.Png
保存,一个用 ImageFormat.Jpeg
保存。
PNG 图片
JPEG 图片
如果您确定您绝对必须使用 JPEG,您可能会发现原始发帖人在这个问题中所做的工作很有帮助。它涉及将图像编解码器和编码参数配置为高质量设置。 .NET Saving jpeg with the same quality as it was loaded
如果是我,我会尽快使用 PNG 格式,因为它是无损的。
关于c# - 调整图像大小时出现质量问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3584328/