Android: Converting a Bitmap to a Monochrome Bitmap (1 Bit per Pixel)

前端 未结 4 1577
一向
一向 2020-12-05 00:57

I want to print a Bitmap to a mobile Bluetooth Printer (Bixolon SPP-R200) - the SDK doesn\'t offer direkt methods to print an in-memory image. So I thought about converting

相关标签:
4条回答
  • 2020-12-05 01:14

    You can convert the image to monochrome 32bpp using a ColorMatrix.

    Bitmap bmpMonochrome = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmpMonochrome);
    ColorMatrix ma = new ColorMatrix();
    ma.setSaturation(0);
    Paint paint = new Paint();
    paint.setColorFilter(new ColorMatrixColorFilter(ma));
    canvas.drawBitmap(bmpSrc, 0, 0, paint);
    

    That simplifies the color->monochrome conversion. Now you can just do a getPixels() and read the lowest byte of each 32-bit pixel. If it's <128 it's a 0, otherwise it's a 1.

    0 讨论(0)
  • 2020-12-05 01:18

    You should convert each pixel into HSV space and use the value to determine if the Pixel on the target image should be black or white:

      Bitmap bwBitmap = Bitmap.createBitmap( bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565 );
      float[] hsv = new float[ 3 ];
      for( int col = 0; col < bitmap.getWidth(); col++ ) {
        for( int row = 0; row < bitmap.getHeight(); row++ ) {
          Color.colorToHSV( bitmap.getPixel( col, row ), hsv );
          if( hsv[ 2 ] > 0.5f ) {
            bwBitmap.setPixel( col, row, 0xffffffff );
          } else {
            bwBitmap.setPixel( col, row, 0xff000000 );
          }
        }
      }
      return bwBitmap;
    
    0 讨论(0)
  • 2020-12-05 01:22

    Converting to monochrome with exact the same size as the original bitmap is not enough to print.

    Printers can only print each "pixel" (dot) as monochrome because each spot of ink has only 1 color, so they must use much more dots than enough and adjust their size, density... to emulate the grayscale-like feel. This technique is called halftoning. You can see that printers often have resolution at least 600dpi, normally 1200-4800dpi, while display screen often tops at 200-300ppi.

    Halftone

    So your monochrome bitmap should be at least 3 times the original resolution in each side.

    0 讨论(0)
  • 2020-12-05 01:23

    Well I think its quite late now to reply to this thread but I was also working on this stuff sometimes back and decided to build my own library that will convert any jpg or png image to 1bpp .bmp. Most printers that require 1bpp images will support this image (tested on one of those :)). Here you can find library as well as a test project that uses it to make a monochrome single channel image. Feel free to change it..:)

    https://github.com/acdevs/1bpp-monochrome-android

    Enjoy..!! :)

    0 讨论(0)
提交回复
热议问题