Converting Bitmap to Grayscale


I’m just going to share this simple snippet to convert your colored bitmap to grayscale. I’ve used this before because my application needs to communicate to a server which will just extract the image features using SURF. It doesn’t really need the color information so we decided that we can remove the color information so save up few kbps and eventually speed up the transfer.

First is to load your colored image to a bitmap. It can be from your camera, filesystem or from the internet. In this example, I’m loading the image from sdcard.

Load the bitmap from file


Bitmap bmp = BitmapFactory.decodeFile("/sdcard/pic.png");

Now we are ready to process this bitmap and convert it into grayscale. We need to create a new  bitmap with the same width and height as our colored bitmap and set its configuration to RGB_565. I haven’t tried using ARGB_8888 and I don’t know what will be the effect of using this but my images don’t have transparency so storing the alpha channel isn’t needed at all.


Bitmap gray = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.RGB_565);

Now, we need to create canvas, where we will draw the new bitmap. The code that converts the colored bitmap to grayscale is just by using ColorMatrixFilter which then can be used as a property of a paint. Then finally, the paint can be used to draw the new bitmap into our canvas.


Canvas canvas = new Canvas(gray);
Paint paint = new Paint();

ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);

ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);

paint.setColorFilter(f);

canvas.drawBitmap(bmp, 0, 0, paint);

Now, the gray bitmap should have the grayscale equivalent of the colored bitmap.

comments powered by Disqus