1

I am here trying to convert my current bitmap in black and white bitmap by writing following method.But it takes very long time to convert because of its for loop of every pixels.Am i wrong here any where? or is there any other way to do this?..Help will be appreciated.Thank you.

My Code:

public Bitmap convert(Bitmap src) {
       final double GS_RED = 0.299;
        final double GS_GREEN = 0.587;
        final double GS_BLUE = 0.114;
        int A, R, G, B;
        final int width = src.getWidth();
        final int height = src.getHeight();

        int pixels[] = new int[width * height];
        int k = 0;
        Bitmap bitmap = Bitmap.createBitmap(width, height, src.getConfig());
        src.getPixels(pixels, 0, width, 0, 0, width, height);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int pixel = pixels[x + y * width];
                A = Color.alpha(pixel);
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
                R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
                pixels[x + y * width] = Color.argb(
                        A, R, G, B);
            }
        }

        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Chirag
  • 27
  • 7
  • Possible duplicate of [how to make the color image to black and white in Android](https://stackoverflow.com/questions/10185443/how-to-make-the-color-image-to-black-and-white-in-android) – Ramesh sambu Dec 20 '17 at 11:55
  • Use ColorMatrices. They work on the whole color map at once, instead of scanning the picture pixel by pixel. And can be used for many different effects. – Phantômaxx Dec 20 '17 at 12:02

1 Answers1

4

You can easily convert rgb image to grayscale using this method without looping through all pixels

public Bitmap toGrayscale(Bitmap bmp)
{        
    int originalwidth, originalheight;
    originalheight = bmp.getHeight();
    originalwidth = bmp.getWidth();    

    Bitmap bmpGrayscale = Bitmap.createBitmap(originalwidth, originalheight, 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(bmp, 0, 0, paint);
    return bmpGrayscale;
}
Basil jose
  • 774
  • 3
  • 11