Convert image to 1 bpp bitmap in .net compact framework

后端 未结 3 2024
攒了一身酷
攒了一身酷 2020-12-03 09:05

I have an image of a signature I am trying to save as 1 bpp bitmap to save file space. The full .NET Framework has the enum PixelFormat.Format1bppIndexed, but

3条回答
  •  既然无缘
    2020-12-03 09:29

    I had to do this in the past for generating black & white reports printed via Bluetooth (color or greyscale images were too large for the printer's buffer). Turned out I had to create the images using native code.

    Here's a snippet:

    private void CreateUnmanagedResources()
    {
        // for safety, clean up anything that was already allocated
        ReleaseUnmanagedResources();
    
        bih = new BITMAPINFOHEADER();
        bih.biBitCount = 1;
        bih.biClrImportant = 0;
        bih.biClrUsed = 0;
        bih.biCompression = 0;
        bih.biHeight = m_cy;
        bih.biPlanes = 1;
        bih.biSize = (uint)(Marshal.SizeOf(typeof(BITMAPINFOHEADER)) - 8); 
        bih.biSizeImage = 0;
        bih.biWidth = m_cx;
        bih.biXPelsPerMeter = 0;
        bih.biYPelsPerMeter = 0;
        bih.clr2 = 0xffffff;
        bih.clr1 = 0x0;
    
        hDC = Win32.CreateCompatibleDC(IntPtr.Zero);
        pBits = IntPtr.Zero;
        hBitmap = Win32.CreateDIBSection(hDC, bih, 1, ref pBits, IntPtr.Zero, 0);
        hbmOld = Win32.SelectObject(hDC, hBitmap);
    }
    
    private void ReleaseUnmanagedResources()
    {
        if (hbmOld != IntPtr.Zero)
            Win32.SelectObject(hDC, hbmOld);
    
        if(hBitmap != IntPtr.Zero)
            Win32.DeleteObject(hBitmap);
    
        if (hDC != IntPtr.Zero)
            Win32.DeleteDC(hDC);
    }
    

    I then used Graphics.FromHdc to get a managed graphics object that I could paint the report onto.

    I did saving with a BinaryWriter, but that was in CF 1.0 days when the Bitmap class didn't have a Save, so you're free and clear there.

提交回复
热议问题