2016-03-25 12 views
0

我有一个问题,这是否可能。我想使用for循环来生成位图,对该位图执行某些操作,然后将其存储在List<Bitmap>中。C#位图列表Flushing

我知道位图可能会占用大量内存,因此我在考虑将位图添加到列表后考虑处理位图。这里是我的代码:

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(); 
} 

此代码后,我有过每个位循环并打印的代码,但位图不在列表中?

在这种情况下,我怎么能不成为记忆猪?

谢谢!

回答

0

如果要存储它们,也可以将BitMaps转换为byte []。这将摆脱潜在的内存泄漏。您也可以考虑将它们转换为Base64字符串,这通常与HTML格式一起使用。

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()); 
     } 
    } 
} 
0

您必须将位图保留在内存中,直到您有没有用于它们。如果你只是要再次使用所有相同的位图,你也可以使用一个using语句来处理每一个位图,因为它像

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

using语句生成会自动处理位图已经与完成后, 。但是,如果需要将位图存储在列表中,则您无权选择,只能在之后处理它们完成与您的任何工作。

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(); 
}