Easiest Black Bitmap

For one program of mine I had a lot of dynamic resource fetching to do. Unfortunately, sometimes a lookup in resources would return null bitmap. Whether that was due to the missing resource or because of a wrong key is of less importance. I didn't want system to crash but I did want for program to crash just because bitmap was missing. But I did want to have that clearly visible so that I could catch it.

One idea was to use dummy resource, e.g.:

item.Image = (bitmap != null) ? bitmap : dummyBitmap;

However, I didn't like that solution due to a potential resource release at other places. Nothing worse then releasing resource in use somewhere else. And I was more in the mood for one-liner - resources be damned.

But how to create an bitmap and color it at the same time (by default, bitmap is transparent)? Well, we could always create one without alpha channel, e.g.:

item.Image = (bitmap != null) ? bitmap : new Bitmap(size, size, PixelFormat.Format8bppIndexed);

This will make your bitmap one big black rectangle. It might not be ideal but it is definitely noticeable.

PS: Since I wanted this only during debugging, my final code ended up being just a smidge more complicated:

item.Image = (bitmap != null) ? bitmap : new Bitmap(size, size, PixelFormat.Format8bppIndexed);
if (bitmap != null) { item.Image = bitmap; }

Leave a Reply

Your email address will not be published. Required fields are marked *