2013-03-15 112 views
2

我有一些圖像,我需要做一些粗糙的重新大小的工作 - 對於這個例子的目的,讓我們只是說我需要增加寬度和高度一個給定的圖像4個像素。 我不確定爲什麼要調用Graphics.DrawImage()拋出一個OOM - 任何建議在這裏將不勝感激。Graphics.DrawImage() - 拋出內存異常

class Program 
{ 
    static void Main(string[] args) 
    { 
     string filename = @"c:\testImage.png"; 

     // Load png from stream 
     FileStream fs = new FileStream(filename, FileMode.Open); 
     Image pngImage = Image.FromStream(fs); 
     fs.Close(); 

     // super-hacky resize 
     Graphics g = Graphics.FromImage(pngImage); 
     g.DrawImage(pngImage, 0, 0, pngImage.Width + 4, pngImage.Height + 4); // <--- out of memory exception?! 

     // save it out 
     pngImage.Save(filename, System.Drawing.Imaging.ImageFormat.Png); 
    } 
} 
+0

您可以在基於原始圖像的'Graphics'對象中繪製較大的圖像嗎? – FlyingStreudel 2013-03-15 17:27:54

回答

2

您的圖形表面僅適合原始大小的圖像。您需要創建一個正確大小的新圖像,並將其用作Graphics對象的源。

Image newImage = new Bitmap(pngImage.Width + 4, pngImage.Height+4); 
Graphics g = Graphics.FromImage(newImage); 
+0

你能解釋一下+4嗎? – Pangamma 2017-08-07 07:14:56

+0

@Pangamma問題是關於將圖像的寬度和高度增加4個像素,因此+4。 – jlew 2017-08-09 20:15:50

+0

Ahhhh哇。 Ahaha。 @Jeff是的,那將是原因。謝謝。我不相信我錯過了。 – Pangamma 2017-08-10 15:33:19

0

你可以試試這個修復嗎?

class Program 
    { 
     static void Main(string[] args) 
     { 
      string filename = @"c:\testImage.png"; 

      // Load png from stream 
      FileStream fs = new FileStream(filename, FileMode.Open); 
      Image pngImage = Image.FromStream(fs); 
      fs.Close(); 

      // super-hacky resize 
      Graphics g = Graphics.FromImage(pngImage); 
      pngImage = pngImage.GetThumbnailImage(image.Width, image.Height, null, IntPtr.Zero); 
      g.DrawImage(pngImage, 0, 0, pngImage.Width + 4, pngImage.Height + 4); // <--- out of memory exception?! 

      // save it out 
      pngImage.Save(filename, System.Drawing.Imaging.ImageFormat.Png); 
     } 
    } 

被這個問題啓發:Help to resolve 'Out of memory' exception when calling DrawImage

1

這可能不會完成你想要做的看到的圖像是如何的大小由FromImage指定的同一個什麼,而是你可以使用Bitmap等級:

using (var bmp = new Bitmap(fileName)) 
{ 
    using (var output = new Bitmap(
     bmp.Width + 4, bmp.Height + 4, bmp.PixelFormat)) 
    using (var g = Graphics.FromImage(output)) 
    { 
     g.DrawImage(bmp, 0, 0, output.Width, output.Height); 

     output.Save(outFileName, ImageFormat.Png); 
    } 
} 
+0

說真的,+4是什麼東西? – Pangamma 2017-08-07 07:15:58

2

我剛剛有同樣的問題。不過,修復輸出Graphics的大小並不能解決我的問題。我意識到,當我在很多圖像上使用代碼時,我試圖使用非常高的質量來繪製消耗太多內存的圖像。

g.CompositingQuality = CompositingQuality.HighQuality; 
g.InterpolationMode = InterpolationMode.HighQualityBicubic; 
g.SmoothingMode = SmoothingMode.HighQuality; 
出來的代碼非常完美註釋這些行後