C#: Dispose() a Bitmap object after call Bitmap.save()?

给你一囗甜甜゛ 提交于 2020-01-01 12:09:42

问题


I have this:

Bitmap bmp = new Bitmap(image);
//image processing
bmp.Save(path + fileName);

and I want to know if I need to call bmp.Dispose() after this code. Thanks in advance.


回答1:


I would use using block and Path.Combine

using(var bmp = new Bitmap(image))
{
    // image processing
    bmp.Save(Path.Combine(path ,fileName));
}



回答2:


Yes.

Better yet, you could wrap your bmp in a using block, this will take care of the disposal for you

using(var bmp = new Bitmap(image))
{
    bmp.Save(...);
}

Save's sole purpose is to save the image to the specified file, it doesn't change the bitmap object




回答3:


There's a simple rule: if you've created a disposable instance and haven't passed it to another ower, you should dispose it. In your code; since you've created Bitmap you're supposed to dispose it as well:

using (Bitmap bmp = new Bitmap(image)) { // <- Creation
  // Image processing
  ...
  bmp.Save(path + fileName);
} // <- You no longer need the bitmap, let's dispose it



回答4:


If you're done with it: yes. Based simply on the fact that

  • it implements IDisposable, and
  • you're done with it

To be honest, those two points are essentially the entire debate - everything else is implementation details. Although in this case the implementation details are probably GDI+ handles, which are definitely worth cleaning up properly. But you can make your life easier with using:

using(var bmp = new Bitmap(image))
{
    // image processing
    bmp.Save(path + fileName);
}



回答5:


Yes, you need to call Dispose() method, otherwise bitmap recources being in use before garbage collertor calls finalizer method. Just use the using operator:

using(var bmp = new Bitmap(image))

    {
        // image processing
        bmp.Save(path + fileName);
    }


来源:https://stackoverflow.com/questions/18119719/c-dispose-a-bitmap-object-after-call-bitmap-save

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!