Context:
Me and my colleagues work alot handling bitmap images via C#.
At the moment, we are also working with the AForge Framework for managing images, and since the methods of the AForge dll work with UnmanagedImage classes, we always need to convert a Bitmap to a UnmanagedImage before starting to use the library.
Simple Piece of Code:
This is how we usually convert the Bitmap to the UnmanagedImage Class
BitmapData bmpData;
Bitmap bmp = AForgeImaging.SetTo24BitsPerPixel(bmp);
bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
UnmanagedImage unmanaged = new UnmanagedImage(bmpData);
The problem is that we always have to do something like this in order to avoid exceptions:
try
{
// Create Unmanaged Image
// Process the Image And Stuff
}
finally
{
// Unlock BitmapBits
}
Our Goal:
Avoid having to surround every piece of code with this try/finally
statement.
Is there any way we can aproach this in order to make it work ?
We've tried to Extend
the bitmap, but since it's Sealed, it's not possible.
Also,writing extension methods such as this example would not work because it needs a static class to Be an Extension Handler
and this would not help us in any ways.
Question:
That said, is there any way we can manage to Write a "Disposable" Bitmap when it comes to the "UnlockBits()" method, without having to write a "Wrapper" ?
By Wrapper i mean a class with a private bitmap attribute
that would
replicate calls to to the bitmap attribute. This would lead us to write every bitmap method
again and just call the method with the same name on the private attribute, which is sort of Meh.
Thanks in advance