dotnet
resource_error
ai_generated
partial
System.OutOfMemoryException: 内存不足。在 System.Drawing.Graphics.FromImage(Image image)
System.OutOfMemoryException: Out of memory. at System.Drawing.Graphics.FromImage(Image image)
ID: dotnet/gdiplus-out-of-memory
78%修复率
85%置信度
1证据数
2023-04-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| .NET 6.0 | active | — | — | — |
| .NET 7.0 | active | — | — | — |
| .NET 8.0 | active | — | — | — |
| .NET Framework 4.8 | active | — | — | — |
根因分析
GDI+ 在从像素格式无效或尺寸超过 2^16 像素的 Image 创建 Graphics 对象时抛出 OutOfMemoryException,通常是由于图像文件损坏或位图过大。
English
GDI+ throws OutOfMemoryException when creating a Graphics object from an Image with invalid pixel format or dimensions exceeding 2^16 pixels, often due to corrupt image files or oversized bitmaps.
官方文档
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.fromimage解决方案
-
在创建 Graphics 前验证图像尺寸:if (image.Width > 65535 || image.Height > 65535) throw new InvalidOperationException("图像过大"); -
使用 Image.Save 以固定格式(如 ImageFormat.Png)重新保存图像,确保有效像素格式。
-
改用 SkiaSharp 或 ImageSharp 替代 System.Drawing.Common 进行跨平台图像处理。
无效尝试
常见但无效的做法:
-
Increase GC memory limit via gcAllowVeryLargeObjects or -gcremove
95% 失败
The error is not about managed memory; GDI+ unmanaged memory is limited by OS and pixel format, not GC.
-
Wrap in try-catch and retry with Thread.Sleep
98% 失败
Retrying does not fix the underlying corrupt image or invalid pixel format; the same error will recur.
-
Set Image.FromFile to use a larger buffer
99% 失败
The error occurs during Graphics creation, not file loading; buffer size is irrelevant.