4

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.

eightShirt
  • 1,457
  • 2
  • 15
  • 29

5 Answers5

6

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

Sayse
  • 42,633
  • 14
  • 77
  • 146
6

I would use using block and Path.Combine

using(var bmp = new Bitmap(image))
{
    // image processing
    bmp.Save(Path.Combine(path ,fileName));
}
eightShirt
  • 1,457
  • 2
  • 15
  • 29
Damith
  • 62,401
  • 13
  • 102
  • 153
  • 1
    it is better to use when you join paths like this case. http://stackoverflow.com/questions/961704/how-do-i-join-two-paths-in-c – Damith Aug 08 '13 at 07:18
4

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
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

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);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

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);
    }
hmnzr
  • 1,390
  • 1
  • 15
  • 24