2011-09-26 72 views
3

調整圖像大小後,我的調整大小函數返回一個新繪製的圖像。我遇到了一個問題,我需要確定返回的Image的文件擴展名應該是什麼。我以前使用的是Image.RawFormat屬性,但每次從此函數返回圖像時,它都有ImageFormat.MemoryBMP,而不是ImageFormat.JpegImageFormat.Gif從ImageFormat.MemoryBMP確定文件類型

所以基本上我的問題是,我如何確定新調整大小的Image應該是什麼文件類型?

public static Image ResizeImage(Image imageToResize, int width, int height) 
     { 
      // Create a new empty image 
      Image resizedImage = new Bitmap(width, height); 

      // Create a new graphic from image 
      Graphics graphic = Graphics.FromImage(resizedImage); 

      // Set graphics modes 
      graphic.SmoothingMode = SmoothingMode.HighQuality; 
      graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; 
      graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; 

      // Copy each property from old iamge to new image 
      foreach (var prop in imageToResize.PropertyItems) 
      { 
       resizedImage.SetPropertyItem(prop); 
      } 

      // Draw the new Image at the resized size 
      graphic.DrawImage(imageToResize, new Rectangle(0, 0, width, height)); 

      // Return the new image 
      return resizedImage; 
     } 

回答

5

調整大小後的圖像不是基於任何文件的格式,它是圖像中像素的未壓縮內存表示。

要將此圖像保存回磁盤,數據需要按所選格式進行編碼,您必須指定該格式。看看Save方法,它將ImageFormat作爲第二個參數,製作最適合您的應用程序的Jpeg或任何格式。

+0

感謝您澄清我對此的理解。 – Chris