0

Hi I want to convert a normal bitmap to monochrome bitmap in Android, how can I do that. I tried to look online but could only find

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);

I want to pass a a bitmap and in return bet a Byte array of the monochrome bitmap.

  public static byte[] toBytes(Bitmap bitmap) {

  }

Any pointers or links please

R

BRDroid
  • 3,920
  • 8
  • 65
  • 143

2 Answers2

1

You can use the ColorMatrix calss to achieve this:

ImageView imgview = (ImageView)findViewById(R.id.imageView_grayscale);
imgview.setImageBitmap(bitmap);

// Apply grayscale filter
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imgview.setColorFilter(filter);

Another example of ClorMatrix approach is covered in this gist.

1

Based on your code snippet:

public static byte[] toMonochromeByteArray(Bitmap bitmap) {
    final Bitmap result = Bitmap.createBitmap(
            bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());

    final Canvas canvas = new Canvas(result);
    final ColorMatrix saturation = new ColorMatrix();
    saturation.setSaturation(0f);

    final Paint paint = new Paint();
    paint.setColorFilter(new ColorMatrixColorFilter(saturation));
    canvas.drawBitmap(bitmap, 0, 0, paint);

    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final Bitmap.CompressFormat compressFormat =
            bitmap.hasAlpha() ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG;
    result.compress(compressFormat, 100, stream);
    result.recycle();

    return stream.toByteArray();
}
Akaki Kapanadze
  • 2,552
  • 2
  • 11
  • 21
  • Hi Akaki, thank you for responding, I tried your method but still the format does not look the same as the logo which works. logo which works - byte array looks like this - getLogoBitmap - array 0x42 0x4D 0x9A 0x4B 0x00 0x00 0x00 0x00 0x00 0x00 0x3E 0x00 0x00 0x00 0x28 0x00 0x00 0x00 signature bitmap which does not work looks like this - signature - array 0xFF 0xD8 0xFF 0xE0 0x00 0x10 0x4A 0x46 0x49 0x46 0x00 0x01 0x01 0x00 0x00 0x01 0x00 0x01 0x00 let me know if you want the full byte array of both to give a better idea can you make any difference between them – BRDroid Sep 25 '19 at 09:06