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);
OutOfMemoryException 操作圖片時,優先檢查矩形座標與尺寸是否越界。Bitmap.Clone 是除建構函式外另一種複製圖片方式,支援像素格式轉換與區域裁剪,威力強大但參數驗證嚴格。