Many people are in trouble and on forums asking why the .Net Bitmap object does not release an image with its .Dispose() method. The Bitmap object (after its destruction too) seems to lock the image file, then we are not able to move or delete that image file through the file system.
This is a known problem and it occurs when we declare and instantiate a Bitmap object and destruct that like in the following code:
[sourcecode language=”vb”] ‘create a bitmap object
Dim myBitmap As New Bitmap("c:myimage.jpg")
‘editing image routines, right here
‘…
‘release all Bitmap object resources
myBitmap.Dispose()
The above code it is formally correct, however in same circumstances the .net garbage collector cannot recognize bitmap’s disposing; Dispose() method leaves the image file in an unusable state, then as MSDN said, we MUST release explicitly any reference after a Dispose() call;
with the following code, You will not encounter any problem, and after Dispose() You can edit, move, delete the image file by the filesystem functions…
[sourcecode language=”vb”] ‘create a bitmap objectDim myBitmap As New Bitmap("c:myimage.jpg")
‘editing image routines, right here
‘…
‘release image reference
While myBitmap IsNot Nothing
myBitmap.Dispose()
myBitmap = Nothing ‘<– tells .net garbage collector to release resources
End While
Happy image editing! 🙂
Leave a Reply