Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

DIB to System.Bitmap

0.00/5 (No votes)
6 Nov 2006 10  
An article on DIB to Bitmap conversion.

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; // (permission problem) 


    IntPtr pBmp = IntPtr.Zero; 
    int status = GdipCreateBitmapFromGdiDib(pDIB, pPix, out pBmp); 

    if ((status == 0) && (pBmp != IntPtr.Zero)) // success 

        return (Bitmap)mi.Invoke(null, new object[] {pBmp}); 

    else 
        return null; // failure 

}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here