2016-09-02 9 views
0

當我執行某些圖像操作時,似乎出現內存不足異常,但我不確定爲什麼,或者確切地說在哪裏。堆棧跟蹤如下:Graphics.Draw內存問題

System.OutOfMemoryException: Out of memory. 
    at System.Drawing.Graphics.CheckErrorStatus(Int32 status) 
    at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 width, Int32 height) 
    at System.Drawing.Bitmap..ctor(Image original, Int32 width, Int32 height) 
    at System.Drawing.Bitmap..ctor(Image original) 

它是由類似的後來跟進秒內存溢出異常:

System.OutOfMemoryException: Out of memory. 
    at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) 

,我認爲是生產,這是的代碼如下:

public static MemoryStream ResizeImage(this Bitmap bitmap, int destHeight, int destWidth, ImageFormat imageFormat) 
    { 
     MemoryStream mem = new MemoryStream(); 
     var xRes = bitmap.VerticalResolution; 
     var yRes = bitmap.HorizontalResolution; 
     var largestRes = xRes > yRes ? xRes : yRes; 
     var factor = Math.Abs(xRes/yRes); 
     bitmap.SetResolution(largestRes, largestRes); 
     if (destHeight == 0) 
      destHeight = (int)(xRes != largestRes ? bitmap.Height/factor : bitmap.Height); 
     if (destWidth == 0) 
      destWidth = (int)(yRes != largestRes ? bitmap.Width/factor : bitmap.Width); 
     using (Bitmap b = new Bitmap(destWidth, destHeight)) 
     { 
      using (Graphics g = Graphics.FromImage((System.Drawing.Image)b)) 
      { 
       g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
       g.DrawImage(bitmap, 0, 0, destWidth, destHeight); 
      } 
      b.Save(mem, imageFormat); 
     } 
     return mem; 
    } 

我知道這是做了很多圖像處理,但是有什麼內在的錯誤嗎?

+0

它有什麼問題,即MemoryStream不能按原樣使用。添加'mem.Position = 0;'有點沒有意義只發布部分堆棧跟蹤btw。不調用您操作的圖像和位圖對象上的Dispose()方法是一個非常常見的錯誤.. –

回答

1

代碼沒問題,但GDI +可以在不支持圖像的像素格式時拋出OutOfMemoryException。

檢查圖像以確保它被支持。