Skip to content

How to create an UnmanagedImage

Anders Gustafsson edited this page Apr 1, 2015 · 4 revisions

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.

Purchase a commercial license of Shim.Drawing for Android, iOS or Windows for unlimited distribution of Portable AForge and Accord based applications on app stores!

Android, €50
iOS, €50
Windows, €50
All platforms, €100

All prices include VAT.

Clone this wiki locally