Recently, I was wondering how to convert a color image into a grayscale image, view the information, and finally achieve the expected effect. Now I am posting the code to share with you:
Public Bitmap ConvertGrayImg (Bitmap img1)
{
Int width = img1.getWidth ();
Int height = img1.getHeight ();
Int [] pix = new int [width * height];
Img1.getPixels (pix, 0, width, 0, 0, width, height); // The third parameter, width, must be the width of the bitmap.
Int alpha = 0xFF <24;
For (int I = 0; I For (int j = 0; j <width; j ++ ){
Int color = pix [width * I + j];
// Remember that the Alpha value should be set to 00. Do not set it to ff. Otherwise, it is not a grayscale image.
Int red = (color & 0x00FF0000)> 16 );
Int green = (color & 0x0000FF00) >>;
Int blue = color & 0x000000FF;
// Here some people will add the values of the three color components and divide them by 3, but this will have some extreme situations, so the ratio is 0.3, 0.59, 0.11.
// It is better
Color = (int) (float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11 );
Color = alpha | (color <16) | (color <| color;
Pix [width * I + j] = color;
}
}
Bitmap result = Bitmap. createBitmap (width, height, Config. RGB_565 );
Result. setPixels (pix, 0, width, 0, 0, width, height );
Return result;
}
Author: zhangyulong882"