What is the maximum resolution of C# .NET Bitmap?
This is a GDI+ limitation imposed by Windows. GDI+ creates a memory-mapped file view for the pixel data of the bitmap. That makes it very efficient, bitmaps tend to be large and the MMF helps to keep the pixel data out of the paging file. RAM pages can simply be discarded and re-read from the file. Also rather notorious, lots of programmers have seen their Save() call fail with a wonky exception when they forgot to dispose the old bitmap.
Windows restricts how large the view on an MMF can be, in other words the amount of data in the file that can be directly addressed, as documented in this MSDN article:
The size of a file mapping object that is backed by a named file is limited by disk space. The size of a file view is limited to the largest available contiguous block of unreserved virtual memory. This is at most 2 GB minus the virtual memory already reserved by the process.
"Largest available continuous block" is the restriction in a 32-bit process, tends to hover around ~600 MB, give or take. The 2 GB limit kicks in on a 64-bit process. Technically GDI+ could bypass this limit by remapping the view. But it doesn't, the LockBits() method (also heavily used internally) would be inefficient and very awkward to use.
To use larger bitmaps you need to move to the successor of GDI+, WIC (Windows Imaging Component). Exposed in .NET through the System.Windows.Media.Imaging namespace.
You are running into the maximum allowed object size within .net. That is covered here: Very large collection in .Net causes out-of-memory exception
Edit: You appear to be running into a limitation of GDI Plus. Hans' answer can provides you with an alternative. If you can live within the limitations, then my answer can provide some guidance.
Knowing that you can calcuate the largest bitmap you can create.
- The max is object size is 2GB:2,147,483,648
- Default bitmap is 32bpp (4 bytes), the largest area we can have is 2GB / 4 = 536,870,912
- If we want a square, the largest we can get is sqrt(2GB/4) = 23,170
So the following code works fine:
Bitmap b = new Bitmap(23170,23170);
But the following fails:
Bitmap b = new Bitmap(23171,23170);
If you want to store an image with larger dimensions, you would have to change the pixel format to a lower number of bpp:
Bitmap b = new Bitmap(65535,65535, PixelFormat.Format4bppIndexed);
The size limit in bytes for the Bitmap file format spec is 2^32 bytes.
You reach this limit faster depending on how many bytes per pixel you use.