2011-12-18 6 views
0

このコードが、サイズが556kbの241kbから600x375までの1280x800以前の画像のサムネイルを作成する理由がわかりません。コードは次のとおりです。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)); 
     } 
    } 
} 

ご協力いただければ幸いです。 よろしくお願いします。 Ben

+0

*サイズ*を変更することは、画像の解像度*を変更することと同じではありません。 画像サイズを小さくすることで、より多くのピクセルがより少ないスペースにパックされます。 –

+0

ほとんどの場合、入力画像の圧縮品質は低く、出力画像の圧縮品質は高くなります。 – Rotem

答えて

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の圧縮アルゴリズムの実装に依存しています。それは悪くないが、そこに良いものがあるかもしれない。

ここで、Saveメソッドで使用する圧縮の種類を判断するために、元の画像のImage.RawFormatプロパティを使用します。私は適切な方法を検索することで様々な成功を収めてきたので、私は一般にImageFormat.Pngをバックアップとして使用します(PNG形式は画像の透明度をサポートしていますが、JPEGはありません)。

関連する問題