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

- **ID:** `dotnet/gdiplus-out-of-memory`
- **Domain:** dotnet
- **Category:** resource_error
- **Verification:** ai_generated
- **Fix Rate:** 78%

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

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| .NET 6.0 | active | — | — |
| .NET 7.0 | active | — | — |
| .NET 8.0 | active | — | — |
| .NET Framework 4.8 | active | — | — |

## Workarounds

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

## Dead Ends

- **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% fail)
- **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% fail)
- **Set Image.FromFile to use a larger buffer** — The error occurs during Graphics creation, not file loading; buffer size is irrelevant. (99% fail)
