BRDroid
BRDroid

Reputation: 4388

How to convert normal bitmap to monochrome bitmap android

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

Upvotes: 0

Views: 970

Answers (2)

Akaki Kapanadze
Akaki Kapanadze

Reputation: 2672

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

Upvotes: 1

Pramod Kumar
Pramod Kumar

Reputation: 11

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.

Upvotes: 1

Related Questions