# System.OutOfMemoryException: 内存不足。在 System.Drawing.Graphics.FromImage(Image image)

- **ID:** `dotnet/gdiplus-out-of-memory`
- **领域:** dotnet
- **类别:** resource_error
- **验证级别:** ai_generated
- **修复率:** 78%

## 根因

GDI+ 在从像素格式无效或尺寸超过 2^16 像素的 Image 创建 Graphics 对象时抛出 OutOfMemoryException，通常是由于图像文件损坏或位图过大。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| .NET 6.0 | active | — | — |
| .NET 7.0 | active | — | — |
| .NET 8.0 | active | — | — |
| .NET Framework 4.8 | active | — | — |

## 解决方案

1. ```
   在创建 Graphics 前验证图像尺寸：if (image.Width > 65535 || image.Height > 65535) throw new InvalidOperationException("图像过大");
   ```
2. ```
   使用 Image.Save 以固定格式（如 ImageFormat.Png）重新保存图像，确保有效像素格式。
   ```
3. ```
   改用 SkiaSharp 或 ImageSharp 替代 System.Drawing.Common 进行跨平台图像处理。
   ```

## 无效尝试

- **Increase GC memory limit via gcAllowVeryLargeObjects or -gcremove** — The error is not about managed memory; GDI+ unmanaged memory is limited by OS and pixel format, not GC. (95% 失败率)
- **Wrap in try-catch and retry with Thread.Sleep** — Retrying does not fix the underlying corrupt image or invalid pixel format; the same error will recur. (98% 失败率)
- **Set Image.FromFile to use a larger buffer** — The error occurs during Graphics creation, not file loading; buffer size is irrelevant. (99% 失败率)
