Introduction
This article describes a way to retrieve an image from a DIB handle to a System.Bitmap
object.
I am developing a TWAIN scanning solution for my enterprise. I have developed code for scanning an image. The only problem was that after an image is scanned, the scanned image is available in memory in DIB format and all I am having is an IntPtr
pointing to the DIB image.
My purpose is to retrieve the scanned image from the DIB handle and show it in a picture box. For that, I need to convert the DIB handle into a Bitmap
object. The following code shows how I solved this problem.
Using the code
Here is a code for the function BitmapFromDIB
which will return you a Bitmap
object from the DIB handle.
This function accepts two parameters
pDIB
: it is a pointer to a DIB which is returned after scanning an image
pPix
: it is a pointer to DIBpixels
Here, we have used the function GdipCreateBitmapFromGdiDib
exported from Gdiplus.dll to get a pointer to a Bitmap
. We then use reflection, and pass this pointer to the static internal
method Bitmap.FromGDIplus(IntPtr pGdiBitmap)
.
using System.Drawing;
using System.Reflection;
[DllImport("GdiPlus.dll",
CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern int GdipCreateBitmapFromGdiDib(IntPtr pBIH,
IntPtr pPix, out IntPtr pBitmap);
public static Bitmap BitmapFromDIB(IntPtr pDIB,IntPtr pPix)
{
MethodInfo mi = typeof(Bitmap).GetMethod("FromGDIplus",
BindingFlags.Static | BindingFlags.NonPublic);
if (mi == null)
return null;
IntPtr pBmp = IntPtr.Zero;
int status = GdipCreateBitmapFromGdiDib(pDIB, pPix, out pBmp);
if ((status == 0) && (pBmp != IntPtr.Zero))
return (Bitmap)mi.Invoke(null, new object[] {pBmp});
else
return null;
}