Example #1
0
        /// <summary>
        /// Creates a FreeImage DIB from a Device Context/Compatible Bitmap.
        /// </summary>
        /// <param name="hbitmap">Handle to the bitmap.</param>
        /// <param name="hdc">Handle to a device context.</param>
        /// <returns>Handle to a FreeImage bitmap.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="hbitmap"/> is null.</exception>
        public unsafe static FIBITMAP CreateFromHbitmap(IntPtr hbitmap, IntPtr hdc)
        {
            if (hbitmap == IntPtr.Zero)
            {
                throw new ArgumentNullException("hbitmap");
            }

            FIBITMAP dib = new FIBITMAP();
            BITMAP   bm;
            uint     colors;
            bool     release;

            if (Gdi.GetObject(hbitmap, sizeof(BITMAP), (IntPtr)(&bm)) != 0)
            {
                dib = Allocate(bm.bmWidth, bm.bmHeight, bm.bmBitsPixel, 0, 0, 0);
                if (!dib.IsNull)
                {
                    colors = GetColorsUsed(dib);
                    if (release = (hdc == IntPtr.Zero))
                    {
                        hdc = Gdi.GetDC(IntPtr.Zero);
                    }

                    if (Gdi.GetDIBits(
                            hdc,
                            hbitmap,
                            0,
                            (uint)bm.bmHeight,
                            GetBits(dib),
                            GetInfo(dib),
                            DIB_RGB_COLORS) != 0)
                    {
                        if (colors != 0)
                        {
                            BITMAPINFOHEADER *bmih = (BITMAPINFOHEADER *)GetInfo(dib);
                            bmih[0].biClrImportant = bmih[0].biClrUsed = colors;
                        }
                    }
                    else
                    {
                        UnloadEx(ref dib);
                    }

                    if (release)
                    {
                        Gdi.ReleaseDC(IntPtr.Zero, hdc);
                    }
                }
            }

            return(dib);
        }