2012-07-13 69 views
1

我正在嘗試裁剪來自字節數組的圖像。不幸的是,我在我的cropImage函數中得到了OutofMemory異常。這部分展示瞭如何將它寫在文件上。OutofMemory異常(裁剪圖像時)

System.IO.MemoryStream ms = new System.IO.MemoryStream(strArr); 

System.Drawing.Rectangle oRectangle = new System.Drawing.Rectangle(); 
oRectangle.X = 50; 
oRectangle.Y = 100; 
oRectangle.Height = 180; 
oRectangle.Width = 240; 

System.Drawing.Image oImage = System.Drawing.Image.FromStream(ms); 
cropImage(oImage, oRectangle); 
name = DateTime.Now.Ticks.ToString() + ".jpg"; 
System.IO.File.WriteAllBytes(context.Server.MapPath(name), strArr); 
context.Response.Write("http://local.x.com/test/" + name); 

,這部分是我的裁剪圖像功能,這是很明顯它是做什麼..

private static System.Drawing.Image cropImage(System.Drawing.Image img, System.Drawing.Rectangle cropArea) 
{ 
    System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img); 
    System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea, 
    bmpImage.PixelFormat); 
    return (System.Drawing.Image)(bmpCrop); 
} 

,這是怎麼構建我的strArr

System.IO.Stream str = context.Request.InputStream; 
int strLen = Convert.ToInt32(str.Length); 
byte[] strArr = new byte[strLen]; 
str.Read(strArr, 0, strLen); 
string st = String.Concat(Array.ConvertAll(strArr, x => x.ToString("X2"))); // try 4 
+1

知道cropArea值是什麼會很有趣。我在想它可能有一些非常大的上限,導致系統嘗試爲bmpImage.Clone(...)的返回值分配一個巨大的圖像。我建議你調試你的應用程序並檢查這個cropArea變量。 – 2012-07-13 09:20:47

+0

請閱讀我的答案。我們在生產中遇到了這個問題。除了使用其他圖像API之外,沒有任何解決方案 – 2012-07-13 09:22:35

+0

@SimonEjsing,它實際上是我在代碼頂部創建的矩形(oRectangle) – 2012-07-13 09:23:15

回答

0

我從字節數組中直接裁剪掉它,它只是工作:)感謝所有盡力幫助我的人。

public byte[] CropImage(int x, int y, int w, int h, byte[] imageBytes) 
    { 
     using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) 
     { 
      ms.Write(imageBytes, 0, imageBytes.Length); 
      System.Drawing.Image img = System.Drawing.Image.FromStream(ms, true); 
      Bitmap bmpCropped = new Bitmap(w, h); 
      Graphics g = Graphics.FromImage(bmpCropped); 

      Rectangle rectDestination = new Rectangle(0, 0, bmpCropped.Width, bmpCropped.Height); 
      Rectangle rectCropArea = new Rectangle(x, y, w, h); 

      g.DrawImage(img, rectDestination, rectCropArea, GraphicsUnit.Pixel); 
      g.Dispose(); 

      MemoryStream stream = new MemoryStream(); 
      bmpCropped.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); 
      return stream.ToArray(); 
     } 
    } 
0

使用System.Drawing中不推薦使用ASP.NET中的命名空間。 MSDN:

System.Drawing命名空間中的類不支持在Windows或ASP.NET服務中使用。試圖從這些應用程序類型中使用這些類可能會產生意想不到的問題,例如服務性能下降和運行時異常。有關受支持的替代方法,請參閱Windows映像組件。

+0

此功能位於我的ashx文件中。你認爲這是它的原因嗎? – 2012-07-13 09:21:08

+0

我100%確定。我們已經在生產應用中體驗過它。請閱讀頂部的http://msdn.microsoft.com/en-us/library/system.drawing.aspx。即使它能在你的盒子上工作,你也不能確定它會在其他盒子上工作。 – 2012-07-13 09:23:08

+0

[MSDN](http://msdn.microsoft.com/zh-cn/library/system.drawing.aspx)表示,「Windows圖像組件」是ASP應用程序的此名稱空間的替代產品。 – Amicable 2012-07-13 09:24:13