I was creating a little tool to do some icon drawing and I ran into an error which I cannot find an explanation for. The first PixelFormat I chose caused an Out of Memory exception. (I chose the first one in the list with an Alpha Channel: Format16bppArgb1555). Simply changing to the next alpha format down the list fixed my problem, but I was curious as to why I was getting the error, so I decided to test all PixelFormats. There are many formats which the documentation says will not work, but these 2 seem like they should.
Why do Format16bppArgb1555
and Format16bppGrayScale
cause Out of Memory exceptions when calling Graphics.FromImage()?
Here is the test code I made:
Bitmap myBitmap=null;
Graphics myGraphics=null;
foreach ( PixelFormat pixFormat in Enum.GetValues(typeof(System.Drawing.Imaging.PixelFormat)))
{
Console.WriteLine();
try
{
myBitmap = new Bitmap(192, 192, pixFormat);
Console.WriteLine("Good Bitmap" + PixFormatToString(pixFormat));
myGraphics = Graphics.FromImage(myBitmap);
}
catch( Exception e)
{
if (myBitmap == null)
{
Console.WriteLine("Bad Bitmap " + PixFormatToString(pixFormat));
Console.WriteLine(e.Message);
}
else
{
Console.WriteLine("Bad Graphics " + PixFormatToString(pixFormat));
Console.WriteLine(e.Message);
}
}
finally
{
if (myBitmap != null)
myBitmap.Dispose();
if (myGraphics != null)
myGraphics.Dispose();
myBitmap = null;
myGraphics = null;
}
}
Here is the compressed output:
UNEXPECTED ERRORS:
Bad Graphics Format16bppArgb1555
Out of memory.
Bad Graphics Format16bppGrayScale
Out of memory.
Expected Errors Bad Bitmaps(not valid to use these PixelFormats for Bitmaps):
Undefined,Max,Indexed,Gdi,Alpha,PAlpha,Extended,Canonical
Expected Errors Bad Graphics(cannot create graphics from indexed formats):
BitmapFormat1bppIndexed,BitmapFormat4bppIndexed,Format8bppIndexed
Good Bitmaps and Graphics:
BitmapFormat16bppRgb555
BitmapFormat16bppRgb565
BitmapFormat24bppRgb
BitmapFormat32bppRgb
BitmapFormat32bppPArgb
BitmapFormat32bppArgb
BitmapFormat48bppRgb
BitmapFormat64bppPArgb
BitmapFormat64bppArgb