2011-12-18 48 views
0

我无法明白为什么此代码会创建之前1280x800的图像的缩略图,尺寸为241kb至600x375,大小为556kb。下面是代码:C# - 在创建相同图像的较小分辨率后图像尺寸增加

using (System.Drawing.Image img = System.Drawing.Image.FromFile(@"c:\images\myImg.jpg")) 
{ 
    int sourceWidth = img.Width; 
    int sourceHeight = img.Height; 
    int thumbHeight, thumbWidth = 0; 
    decimal ratio = decimal.Divide(sourceHeight, sourceWidth); 
    if (sourceHeight > 600 || sourceWidth > 800) 
    { 
     if (ratio >= 1) // Image is higher than it is wide. 
     { 
      thumbHeight = 800; 
      thumbWidth = Convert.ToInt32(decimal.Divide(sourceWidth, sourceHeight) * thumbHeight); 
     } 
     else // Image is wider than it is high. 
     { 
      thumbWidth = 600; 
      thumbHeight = Convert.ToInt32(decimal.Divide(sourceHeight, sourceWidth) * thumbWidth); 
     } 

     using (Bitmap bMap = new Bitmap(thumbWidth, thumbHeight)) 
     { 
      Graphics gr = Graphics.FromImage(bMap); 

      gr.SmoothingMode = SmoothingMode.HighQuality; 
      gr.CompositingQuality = CompositingQuality.HighQuality; 
      gr.InterpolationMode = InterpolationMode.High; 

      Rectangle rectDestination = new Rectangle(0, 0, thumbWidth, thumbHeight); 

      gr.DrawImage(img, rectDestination, 0, 0, sourceWidth, sourceHeight, GraphicsUnit.Pixel); 

      bMap.Save(HttpContext.Current.Server.MapPath("~/i/" + filename + "_" + fileExtension)); 
     } 
    } 
} 

任何帮助将不胜感激。 谢谢, 本

+0

更改*尺寸*与改变图像的*分辨率*不同。 您所做的只是缩小图像尺寸,导致更多的像素被打包到更小的空间中。 – 2011-12-18 06:15:16

+0

很可能,输入图像的压缩质量较低,而输出图像的压缩质量较高。 – Rotem 2011-12-18 06:29:12

回答

3

您正在保存的图像,使用jpeg压缩压缩作为一个位图图像没有压缩。该问题的行是在这里:

bMap.Save(HttpContext.Current.Server 
        .MapPath("~/i/" + filename + "_" + fileExtension)); 

仅仅因为你有一个不同的文件扩展名保存它不会使生成的图像文件的JPEG图像。您需要使用Bitmap.Save overloads之一来指定要保存为的图像的格式。例如,

//Creating a second variable just for readability sake. 
var resizedFilePath = HttpContext.Current.Server 
      .MapPath("~/i/" + filename + "_" + fileExtension); 
bMap.Save(resizedFilePath, ImageFormat.Jpeg); 

当然,您正在依靠Microsoft的压缩算法实现。这并不坏,但可能会有更好的。

现在,您可以做的是使用原始图像的Image.RawFormat属性来确定在Save方法中使用的压缩类型。我有不同的成功检索适当的方法,所以我通常使用ImageFormat.Png作为备份(Png格式支持图像透明度,Jpeg不)。