Click here to Skip to main content
13,297,547 members (42,068 online)
Click here to Skip to main content
Add your own
alternative version

Stats

95.5K views
41 bookmarked
Posted 6 Nov 2006

DIB to System.Bitmap

, 6 Nov 2006
Rate this:
Please Sign up or sign in to vote.
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

Share

About the Author

bijulsoni
Software Developer Microsoft
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionPointer Pin
stixoffire6-Nov-14 10:23
memberstixoffire6-Nov-14 10:23 
GeneralGreat article Pin
Lee.21-Jul-13 16:48
memberLee.21-Jul-13 16:48 
Questionthank you Pin
kevingif4-Mar-13 0:05
memberkevingif4-Mar-13 0:05 
QuestionAssume this is public domain or is there any license? Pin
sbarnes18-Sep-12 10:06
membersbarnes18-Sep-12 10:06 
QuestionHow to convert a bitmap to dib handle ? Pin
vbilici26-Jun-12 4:54
membervbilici26-Jun-12 4:54 
Questiontnx Pin
Mojtaba Candovani5-Mar-12 8:57
memberMojtaba Candovani5-Mar-12 8:57 
GeneralCreating Bitmap from DIB Pin
a.stacchetti.ibed27-Apr-11 5:19
membera.stacchetti.ibed27-Apr-11 5:19 
GeneralGreat code, but doesn't work in WPF Pin
patrickveenstra8-Aug-08 4:37
memberpatrickveenstra8-Aug-08 4:37 
GeneralRe: Great code, but doesn't work in WPF Pin
patrickveenstra8-Aug-08 8:27
memberpatrickveenstra8-Aug-08 8:27 
GeneralRe: Great code, but doesn't work in WPF Pin
bijulsoni8-Aug-08 8:44
memberbijulsoni8-Aug-08 8:44 
GeneralRe: Great code, but doesn't work in WPF Pin
patrickveenstra8-Aug-08 9:07
memberpatrickveenstra8-Aug-08 9:07 
GeneralRe: Great code, but doesn't work in WPF Pin
patrickveenstra9-Aug-08 1:50
memberpatrickveenstra9-Aug-08 1:50 
GeneralCreating Bitmap from DIB without PInvoke (Code inside) Pin
Renegade223-Jun-08 23:24
memberRenegade223-Jun-08 23:24 
GeneralRe: Creating Bitmap from DIB without PInvoke (Code inside) Pin
samorim4-Sep-08 15:31
membersamorim4-Sep-08 15:31 
GeneralRe: Creating Bitmap from DIB without PInvoke (Code inside) Pin
bijulsoni4-Sep-08 21:55
memberbijulsoni4-Sep-08 21:55 
GeneralRe: Creating Bitmap from DIB without PInvoke (Code inside) [modified] Pin
oobayly18-Dec-08 13:13
memberoobayly18-Dec-08 13:13 
GeneralRe: Creating Bitmap from DIB without PInvoke (Code inside) Pin
HPMV31-Jan-10 16:02
memberHPMV31-Jan-10 16:02 
GeneralRe: Creating Bitmap from DIB without PInvoke (Code inside) Pin
lytico3-Apr-09 15:56
memberlytico3-Apr-09 15:56 
Thanks a lot!
I modified the stuff a little bit to do the whole thing without copying (as bitmaps can get very big), and included changes from oobayly:



using System;
using System.IO;
 
namespace Limaki.Drawing {
    public class BitmapFromDibStream:Stream {
        Stream dib = null;
        byte[] header = null;
        public BitmapFromDibStream(Stream dib) {
            this.dib = dib;
            makeHeader();
        }
        private void makeHeader() {
            BinaryReader reader = new BinaryReader(dib);
 
            int headerSize = reader.ReadInt32();
            int pixelSize = (int) dib.Length - headerSize;
            int fileSize = 14 + headerSize + pixelSize;
 
            MemoryStream bmp = new MemoryStream(14);
            BinaryWriter writer = new BinaryWriter(bmp);
 

 
            /* Get the palette size
                   * The Palette size is stored as an int32 at offset 32
                   * Actually stored as number of colours, so multiply by 4
                   */
            dib.Position = 32;
            int paletteSize = 4 * reader.ReadInt32();
 
            // Get the palette size from the bbp if none was specified
            if ( paletteSize == 0 ) {
                /* Get the bits per pixel
                     * The bits per pixel is store as an int16 at offset 14
                     */
                dib.Position = 14;
                int bpp = reader.ReadInt16();
 
                // Only set the palette size if the bpp < 16
                if ( bpp < 16 )
                    paletteSize = 4 * ( 2 << ( bpp - 1 ) );
            }
 
            // 1. Write Bitmap File Header:			 
            writer.Write((byte) 'B');
            writer.Write((byte) 'M');
            writer.Write(fileSize);
            writer.Write((int) 0);
            writer.Write(14 + headerSize+paletteSize);
            header = bmp.GetBuffer();
            writer.Close();
            dib.Position = 0;
        }
 
        public override int Read ( byte[] buffer, int offset, int count ) {
            
            int dibCount = count;
            int dibOffset = offset - 14;
            int result = 0;
            if (_position&lt;14){
                int headerCount = Math.Min(count + (int)_position, 14);
                Array.Copy(header, _position, buffer, offset, headerCount);
                dibCount -= headerCount;
                _position += headerCount;
                result = headerCount;
            }
            if ( _position &gt;= 14 ) {
                result += dib.Read(buffer, offset + result, dibCount);
                _position = 14 + dib.Position;
            }
            return (int)result;
        }
        public override bool CanRead {
            get { return true; }
        }
 
        public override bool CanSeek {
            get { return false; }
        }
 
        public override bool CanWrite {
            get { return false; }
        }
 
        public override void Flush () {
                
        }
 
        public override long Length {
            get { return 14 + dib.Length; }
        }
 
        private long _position = 0;
        public override long Position {
            get { return _position; }
            set { 
                _position = value;
                if ( _position > 14 )
                    dib.Position = _position - 14;
            }
        }
 
        
 
        public override long Seek ( long offset, SeekOrigin origin ) {
            throw new Exception("The method or operation is not implemented.");
        }
 
        public override void SetLength ( long value ) {
            throw new Exception("The method or operation is not implemented.");
        }
 
        public override void Write ( byte[] buffer, int offset, int count ) {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}


Usage:


Stream stream = dataObject.GetData(DataFormats.Dib) as Stream;
BitmapFromDibStream bmp = new BitmapFromDibStream(stream);
Image image = new Bitmap(bmp);


cheers,
lytico
limada
GeneralRe: Creating Bitmap from DIB without PInvoke (Code inside) Pin
tamerqatar5-Nov-10 20:46
membertamerqatar5-Nov-10 20:46 
GeneralAwesome code Pin
ferchitu29-Apr-08 11:55
memberferchitu29-Apr-08 11:55 
Questionthanks but how to get the pointer to DIBpixels? Pin
duyong0610200214-Apr-08 22:12
memberduyong0610200214-Apr-08 22:12 
AnswerRe: thanks but how to get the pointer to DIBpixels? Pin
bijulsoni16-Apr-08 12:14
memberbijulsoni16-Apr-08 12:14 
AnswerRe: thanks but how to get the pointer to DIBpixels? Pin
q325mg4-Feb-10 13:57
memberq325mg4-Feb-10 13:57 
GeneralGdipCreateBitmapFromGdiDib return values Pin
rborn22-Dec-06 4:38
memberrborn22-Dec-06 4:38 
GeneralRe: GdipCreateBitmapFromGdiDib return values Pin
AmagaeruOtoko14-Sep-07 5:51
memberAmagaeruOtoko14-Sep-07 5:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 6 Nov 2006
Article Copyright 2006 by bijulsoni
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid