简体   繁体   中英

C# Bitmap List Flushing

I have a question as to whether or not this is possible. I would like to use a for loop to generate a bitmap, do something to that bitmap, and then store it in a List<Bitmap> .

I understand that bitmaps can be memory heavy, so I was thinking about disposing of the bitmap after I add it to the list. Here is my code:

List<Bitmap> listOfBitMaps = new List<Bitmap>();

foreach (string thingImLooping in ThingImLoopingThrough)
{
    Bitmap bmp = new Bitmap(1250, 1250);

    // do stuff to bitmap
    listofBitMaps.Add(bmp);
    bmp.Dispose();
}

After this code, I have code that loops through each bitmap and prints it, but the bitmaps are not in the list?

How can I not be a memory hog in this case?

Thank you!

You will have to keep the Bitmaps in memory till you have no use for them. If you are just going to use all the same Bitmaps again, you could instead use a using statement to process each bitmap as it is generated like

using(Bitmap bmp = new Bitmap(1250, 1250)) {
    //Do stuff to bitmap
    //Print bitmap
} // bmp is automatically disposed after this block ends

The using statement will automatically dispose the bitmap after it has been done with. If, however, you need to store the Bitmaps in a list, you have no option but to dispose them after finishing whatever work you have with them.

List<Bitmap> listOfBitMaps = new List<Bitmap>();

foreach (string thingImLooping in ThingImLoopingThrough)
{
    Bitmap bmp = new Bitmap(1250, 1250);
    //Do stuff to bitmap
    listofBitMaps.Add(bmp);
}

foreach (var bmp in listOfBitMaps)
{
    // Print, process, do whatever to bmp
    bmp.Dispose();
}

You can also convert the BitMaps to byte[] when you want to store them. That will get rid of potential memory leaks. You can also look into converting them to Base64 strings, which is commonly used with HTML format.

List<byte[]> listOfBitMaps = new List<byte[]>();

foreach (string thingImLooping in ThingImLoopingThrough)
{
    using (Bitmap bmp = new Bitmap(1250, 1250))
    {

        // do stuff to bitmap
        using (MemoryStream stream = new MemoryStream())
        {
            image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            listofBitMaps.Add(stream.ToArray());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM