Convert Bitmap Image to gray - Android Graphics

Android examples for Graphics:Bitmap Color

Description

Convert Bitmap Image to gray

Demo Code


//package com.java2s;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

public class Main {

    public static Bitmap gray2Binary(Bitmap graymap) {
        ////  w ww  .  jav a 2  s. com
        int width = graymap.getWidth();
        int height = graymap.getHeight();
        //
        Bitmap binarymap = null;
        binarymap = graymap.copy(Config.ARGB_8888, true);
        //
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                //
                int col = binarymap.getPixel(i, j);
                //alpha
                int alpha = col & 0xFF000000;
                //RGB
                int red = (col & 0x00FF0000) >> 16;
                int green = (col & 0x0000FF00) >> 8;
                int blue = (col & 0x000000FF);
                // X = 0.3?R+0.59?G+0.11?BXRGB
                int gray = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
                //
                if (gray <= 95) {
                    gray = 0;
                } else {
                    gray = 255;
                }
                // ARGB
                int newColor = alpha | (gray << 16) | (gray << 8) | gray;
                //
                binarymap.setPixel(i, j, newColor);
            }
        }
        return binarymap;
    }
}

Related Tutorials