Monday, January 9, 2012

Convert color image into black & white image in android

For converting color image into Black and white image, we need set the image saturation into 0.

Using the below mention code we can convert the color image into Black and white image.


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class BlackAndWhiteImageActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ImageView orginalImageView = (ImageView) findViewById(R.id.image);
        ImageView blackImageView = (ImageView) findViewById(R.id.blackimage);

        Bitmap sample = BitmapFactory.decodeResource(getResources(),
                R.drawable.sample);

        orginalImageView.setBackgroundDrawable(new BitmapDrawable(sample));
        blackImageView.setBackgroundDrawable(new BitmapDrawable(
                convertColorIntoBlackAndWhiteImage(sample)));
    }

    private Bitmap convertColorIntoBlackAndWhiteImage(Bitmap orginalBitmap) {
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(0);

        ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
                colorMatrix);

        Bitmap blackAndWhiteBitmap = orginalBitmap.copy(
                Bitmap.Config.ARGB_8888, true);

        Paint paint = new Paint();
        paint.setColorFilter(colorMatrixFilter);

        Canvas canvas = new Canvas(blackAndWhiteBitmap);
        canvas.drawBitmap(blackAndWhiteBitmap, 0, 0, paint);

        return blackAndWhiteBitmap;
    }
}




Here is the main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView android:layout_width="fill_parent"
        android:layout_height="210dp" android:id="@+id/image" />
    <ImageView android:layout_width="fill_parent"
        android:layout_height="210dp" android:id="@+id/blackimage" />
</LinearLayout>

Final Result:


3 comments:

  1. It's very helpful. Thank you Muthukrishnan

    ReplyDelete
  2. This actually converting the image to grayscale, not black and white. But thanks for the sample.

    ReplyDelete