Convert a Bitmap to GrayScale in Android

leparlon picture leparlon · Jul 30, 2010 · Viewed 76.1k times · Source

I am new to this site, and I come with a question about Android.

Is there any way to convert a Bitmap to grayscale? I know how to draw a grayscale bitmap (using canvas operations: http://www.mail-archive.com/[email protected]/msg38890.html) but I really need The actual bitmap in gray colors (or at least something that could be converted to a bitmap later on). Do I have to implement it by hand (pixel by pixel operations)?

I've searched a lot, and still could not find. Anyone knows a easy/efficient way to do it?

Thanks a lot!

Answer

leparlon picture leparlon · Aug 2, 2010

OH, yes, it does. I was using it wrong, thanks for pointing it out to me. (Sorry for the useless question) Here is the end code (heavily based on the one linked) since it may help someone:

public Bitmap toGrayscale(Bitmap bmpOriginal)
{        
    int width, height;
    height = bmpOriginal.getHeight();
    width = bmpOriginal.getWidth();    

    Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(bmpGrayscale);
    Paint paint = new Paint();
    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);
    ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
    paint.setColorFilter(f);
    c.drawBitmap(bmpOriginal, 0, 0, paint);
    return bmpGrayscale;
}

Any remarks or comments on it are very welcome.

Thanks