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

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.fromimage

解决方案

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

无效尝试

常见但无效的做法:

  1. 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.

  2. 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.

  3. Set Image.FromFile to use a larger buffer 99% 失败

    The error occurs during Graphics creation, not file loading; buffer size is irrelevant.