Android: Convert Grayscale to Binary Image

一笑奈何 提交于 2019-12-01 14:33:49

First, you get a NullReferenceException because bmpBinary is NULL.
Second, to get one Color chanel you can use int red = Color.red(pixel);
Third, to set a pixel white use bmpBinary.setPixel(x, y, 0xFFFFFFFF);

I modified your code a bit:

public Bitmap toBinary(Bitmap bmpOriginal) {
    int width, height, threshold;
    height = bmpOriginal.getHeight();
    width = bmpOriginal.getWidth();
    threshold = 127;
    Bitmap bmpBinary = Bitmap.createBitmap(bmpOriginal);

    for(int x = 0; x < width; ++x) {
        for(int y = 0; y < height; ++y) {
            // get one pixel color
            int pixel = bmpOriginal.getPixel(x, y);
            int red = Color.red(pixel);

            //get binary value
            if(red < threshold){
                bmpBinary.setPixel(x, y, 0xFF000000);
            } else{
                bmpBinary.setPixel(x, y, 0xFFFFFFFF);
            }

        }
    }
    return bmpBinary;
}

An even better way is not to use just the value of one color chanel but a weighted average of red green and blue for example:

int gray = (int)(red * 0.3 + green * 0.59 + blue * 0.11);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!