2010-08-27 92 views
4

我使用此代码来调整图像大小。但结果不好,我想要最好的质量。我知道它的低质量,因为我也调整了与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; 
    } 
+0

我知道它只是调整大小,但它值得说你正在比较一个JavaScript功能1000美元的专业图形软件。所以它有可能得到不同的结果。 – Iznogood 2010-08-27 13:02:49

+0

其不是javascript函数它的c#,我知道有一种方法可以用c# – beratuslu 2010-08-27 13:25:41

+0

[ImageResizing.Net](http://imageresizing.net)库会给你最好的质量,并处理[29+图像调整大小陷阱](http://nathanaeljones.com/163/20-image-resizing-pitfalls/)。看看后面的链接,以获得提高质量的提示 - 如果您希望免费的开放源代码解决方案为您处理所有边缘案例,请查看前者。 – 2011-08-02 23:15:20

回答

3

这是我使用的例程。也许你会发现它很有用。这是一种扩展方法,可以启动。唯一的区别是,我省略代码保持纵横比,这你可以只在作为容易堵塞

这种扩展方法的
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格式,因为它是无损的。

+0

同样的问题继续 – beratuslu 2010-08-27 13:21:35

+0

@berotomanya:有趣的。我一直很高兴这个例程的质量。如果您可以发布一个与PhotoShop结果相比不会调整大小的图像示例,这将会很有帮助。另外,了解用什么格式保存图像会很有趣。如果使用损耗.jpg格式,这可能是质量问题的根源。 – kbrimington 2010-08-27 13:43:16

+0

1.原始图像:http://img841.imageshack.us/img841/147/pron1.jpg 2. Photoshop调整大小:http://img835.imageshack.us/img835/9956/photoshopc.jpg 3.程序化调整大小:http://img198.imageshack.us/img198/5216/270as.jpg 正如您所看到的,通过Photoshop调整大小的图像大小为17kb,另一方面,程序化的大小为4kb。而且质量肯定很差(特别是当你的顾客是婚礼房子时)。 – beratuslu 2010-08-27 14:08:30

相关问题