Esempio n. 1
0
    public static byte[] GetByteArray(Bitmap image)
    {
        IntPtr hbmOld;
        IntPtr hBitmap;
        IntPtr hDC;
        // create infoheader
        BITMAPINFOHEADER bih = new BITMAPINFOHEADER(1, image.Height, image.Width);
        // set black and white for 1 bit color palette
        // create fileheader and get data size
        uint             sizeOfImageData;
        BITMAPFILEHEADER bfh = new BITMAPFILEHEADER(bih, out sizeOfImageData);

        // create device context in memory
        hDC = Win32.CreateCompatibleDC(IntPtr.Zero);
        // create a 1 bpp DIB
        IntPtr pBits = IntPtr.Zero;

        hBitmap = Win32.CreateDIBSection(hDC, ref bih, 1, ref pBits, IntPtr.Zero, 0);
        // selet DIB into device context
        hbmOld = Win32.SelectObject(hDC, hBitmap);
        using (Graphics g = Graphics.FromHdc(hDC))
        {
            g.DrawImage(image, 0, 0);
        }
        byte[] imageData = new byte[sizeOfImageData];
        byte[] fileData;
        using (MemoryStream ms = new MemoryStream((int)bfh.bfSize))
        {
            using (BinaryWriter w = new BinaryWriter(ms))
            {
                bfh.Store(w);
                // store bitmapinfoheader with 1 bpp color palette for black and white
                bih.Store(w, new uint[] { (uint)0x0, (uint)0xffffff });
                // copy image data into imageData buffer
                Marshal.Copy(pBits, imageData, 0, imageData.Length);
                // write imageData to stream
                w.Write(imageData);
                w.Close();
            }
            fileData = ms.GetBuffer();
            ms.Close();
        }
        // select old object
        if (hbmOld != IntPtr.Zero)
        {
            Win32.SelectObject(hDC, hbmOld);
        }
        // delete memory bitmap
        if (hBitmap != IntPtr.Zero)
        {
            Win32.DeleteObject(hBitmap);
        }
        // delete memory device context
        if (hDC != IntPtr.Zero)
        {
            Win32.DeleteDC(hDC);
        }
        return(fileData);
    }
Esempio n. 2
0
        public static Bitmap CreateDIB(int x, int y)
        {
            //Set up a BitmapHeader
            Int32 Depth = DetermineColorDepth.getdepth();
            BITMAPINFOHEADER bmpInfo = new BITMAPINFOHEADER((short) Depth, x, y);
            BITMAPFILEHEADER bmpFile = new BITMAPFILEHEADER(bmpInfo);

            byte[] buffer = new byte[bmpFile.bfSize];

            MemoryStream m = new MemoryStream(buffer);
            using (BinaryWriter writer = new BinaryWriter(m))
            {
                bmpFile.Store(writer);
                bmpInfo.Store(writer, false);
                m.Seek(0, SeekOrigin.Begin);
                return new Bitmap(m);
            }
        }