-
Notifications
You must be signed in to change notification settings - Fork 96
How to create an UnmanagedImage
It seems to be fairly common in .NET applications using AForge to initialize an UnmanagedImage
object from a Bitmap
object like this:
Bitmap bitmap;
...
BitmapData bitmapData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly, bitmap.PixelFormat);
UnmanagedImage unmanagedImage = new UnmanagedImage(bitmapData);
...
... // operate on unmanagedImage
...
bitmap.UnlockBits(bitmapData);
However, this approach does not work when using Portable AForge! To avoid unwanted over-use of the Shim.Drawing assembly most of its API is declared internal
i.e. it is not publicly exposed to other components.
Typical examples are the LockBits
and UnlockBits
methods in the Bitmap
class which are minimal implementations solely intended to support the requirements of the AForge and Accord class libraries. To avoid that these methods are accidentally used from third-party applications, the methods are declared internal
.
The above code snippet will thus not compile in a class library or application that is consuming Shim.Drawing for example via a Portable AForge class library. Fortunately, there is a very simple workaround:
UnmanagedImage unmanagedImage = UnmanagedImage.FromManagedImage(bitmap);
Thus, no need to lock and unlock the bitmap via a temporary BitmapData
object, simply construct the UnmanagedImage
directly from the Bitmap
object via the static UnmanagedImage.FromManagedImage
method.