How to convert a color image to a grayscale image in Android

Source: Internet
Author: User

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"
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.