dotnet resource_error ai_generated partial

System.OutOfMemoryException: Out of memory. at System.Drawing.Graphics.FromImage(Image image)

ID: dotnet/gdiplus-out-of-memory

Also available as: JSON · Markdown · 中文
78%Fix Rate
85%Confidence
1Evidence
2023-04-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
.NET 6.0 active
.NET 7.0 active
.NET 8.0 active
.NET Framework 4.8 active

Root Cause

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

中文

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

Official Documentation

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

Workarounds

  1. 85% success Validate image dimensions before creating Graphics: if (image.Width > 65535 || image.Height > 65535) throw new InvalidOperationException("Image too large");
    Validate image dimensions before creating Graphics: if (image.Width > 65535 || image.Height > 65535) throw new InvalidOperationException("Image too large");
  2. 75% success Re-save the image with a valid pixel format using Image.Save with a fixed format like ImageFormat.Png before drawing.
    Re-save the image with a valid pixel format using Image.Save with a fixed format like ImageFormat.Png before drawing.
  3. 95% success Use SkiaSharp or ImageSharp instead of System.Drawing.Common for cross-platform image processing.
    Use SkiaSharp or ImageSharp instead of System.Drawing.Common for cross-platform image processing.

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. Increase GC memory limit via gcAllowVeryLargeObjects or -gcremove 95% fail

    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% fail

    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% fail

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