2010-09-27 27 views
1

我正在開發一項服務,用戶可以在其中上載圖像並將其保存在庫中。我想保留原始文件(這樣人們可以上傳高分辨率圖像),但也可以將圖像的副本作爲縮略圖使用。C#:調整圖像大小時保留每個平面的位數

我的問題是縮略圖「權重」比原始文件更多,按比例。當我檢查每個文件(在XnView中)的基本屬性時,我可以看到原始文件例如以每個平面32位保存,而源文件例如每個平面只有24位。

在仍使用壓縮的情況下複製原始文件的正確方法是什麼?這是代碼摘錄:

private void ResizeImage(string originalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider, string directory) 
    { 
     System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(originalFile); 

     // Prevent using images internal thumbnail 
     FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); 
     FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); 

     if (OnlyResizeIfWider) 
     { 
      if (FullsizeImage.Width <= NewWidth) 
      { 
       NewWidth = FullsizeImage.Width; 
      } 
     } 

     int NewHeight = FullsizeImage.Height * NewWidth/FullsizeImage.Width; 
     if (NewHeight > MaxHeight) 
     { 
      // Resize with height instead 
      NewWidth = FullsizeImage.Width * MaxHeight/FullsizeImage.Height; 
      NewHeight = MaxHeight; 
     } 

     System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); 

     // Clear handle to original file so that we can overwrite it if necessary 
     FullsizeImage.Dispose(); 

     // Save resized picture 
     NewImage.Save(directory + Path.DirectorySeparatorChar + NewFile); 
    } 
+0

您的意思是每像素*位? – 2010-09-27 18:38:52

回答

0

我建議您將圖像保存爲PNG或JPEG流。這將會更有效率。考慮到縮略圖不是原始數據,對其應用強大的壓縮可能是可以的(QF < 60)。我曾經設法以不到1000字節的速度獲得有用的JPEG圖像。在那個時候,他們太小了,你可以考慮把它們放在數據庫而不是磁盤上。

編輯:

而要回答這個問題,的GetThumbnailForImage()結果(完全讀的問題:))之後,又是一個Image這樣你就可以調用它的保存方法,重載的一個可以讓你指定使用哪種壓縮。

0

與其調用GetThumbnailImage,您可以創建所需大小的新圖像和所需的PixelFormat,然後將原始圖像縮放到該圖像中。

System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(originalFile); 

// Create a bitmap that's NewWidth x NewHeight 
Bitmap bmp = new Bitmap(NewWidth, NewHeight, PixelFormat.Format24bppRgb); 

// Get a Graphics object for that image and draw the original image into it 
using (Graphics g = Graphics.FromImage(bmp)) 
{ 
    g.DrawImage(FullsizeImage, 0, 0, NewWidth, NewHeight); 
} 

// you now have a 24bpp thumbnail image