首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

GDI+ 常見問題 (2):Bitmap.Clone 引發 OutOfMemoryException

     編輯:關於.NET

現象

Bitmap bmpTemp = new Bitmap(image);
Bitmap bmp = new Bitmap(bmpTemp);
bmpTemp.Dispose();

Bitmap bmp2 = bmp.Clone(new Rectangle(1, 1, bmp.Width, bmp.Height), PixelFormat.Format24bppRgb);
// System.OutOfMemoryException

異常無 ErrorCode、InnerException 為 null。Marshal.GetLastWin32Error() 回傳 2(ERROR_FILE_NOT_FOUND),與實際無關。

根因

Rectangle 參數為 (1, 1, Width, Height),實際區域右/下邊界超出原圖範圍(有效範圍應為 (0, 0, Width, Height) 或 (1, 1, Width-1, Height-1))。MSDN 明確說明:rect 超出邊界拋 OutOfMemoryException,寬/高為 0 拋 ArgumentException。這屬於框架封裝缺陷:邊界檢查應在進入原生碼前完成,拋出語義正確的異常。

正確寫法

// 複製整圖
Bitmap bmp2 = bmp.Clone(new Rectangle(0, 0, bmp.Width, bmp.Height), PixelFormat.Format24bppRgb);

// 複製子區域(例如去掉 1 像素邊框)
Bitmap bmp2 = bmp.Clone(new Rectangle(1, 1, bmp.Width - 2, bmp.Height - 2), PixelFormat.Format24bppRgb);

教訓

  • GDI+ 托管封裝錯誤訊息具誤導性,遇到 OutOfMemoryException 操作圖片時,優先檢查矩形座標與尺寸是否越界。
  • Bitmap.Clone 是除建構函式外另一種複製圖片方式,支援像素格式轉換與區域裁剪,威力強大但參數驗證嚴格。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved