I have an application that when it starts it reads a GIF, extracts multiple bitmaps from the GIF and then makes this bitmaps available throughout the application for drawing in other classes. For example:
This way, I can access all three bitmaps in other classes by simply using:
etc.
I open up several GIFs this way and extract sub-images from them to be used in my program. In the end there are lots of these bitmaps, even though they are quite small (less than 100×100 px).
While this works fine, is there a more optimal way of doing this? Should I avoid static modifier with Bitmaps and can it cause memory problems when there are multitudes of these bitmaps?
Static variable isn’t a huge issue (that’s a choice to preload). I hope you’re using something more forward-compatible like a Dictionary<string, Bitmap> in production code (retrieving the bitmaps by a configurable constant doesn’t lock you down to a precise number of preloaded images).
If you don’t have the RAM to preload, static isn’t going to make that worse.
I’m unclear which Bitmap class you’re using; the .NET 5.0 System.Drawing version doesn’t have a Clone with that signature. What will make the RAM loading worse, is not arranging to call Dispose on something that implements that interface [which System.Drawing.Bitmap does]. That is, C# 9.0 syntax likely would be
for not leaking the actual image data.
The pixelformat is missing from the Clone method signature, I forgot to paste it from code. Each bitmap actually has a unique identifier, so retrieving them is isn’t a problem.
using statement is a good catch, thanks.