如何在Android中使彩色图像变为黑白

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10185443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:47:08  来源:igfitidea点击:

how to make the color image to black and white in Android

androidcolors

提问by lakshman

I wanted to know the way to convert the color image (which i am downloading from net) to black and white when i am displaying it to the user in android. can anybody found this requirement in any of your android work. Please let me know.

我想知道当我在 android 中向用户显示彩色图像(我从网上下载)转换为黑白的方法。任何人都可以在您的任何 android 工作中找到这个要求。请告诉我。

Thanks Lakshman

谢谢拉克什曼

回答by Munish Kapoor

Hi you can make the image black n white using contrast.

嗨,您可以使用对比度使图像变黑变白。

See the code..

看代码。。

public static Bitmap createContrast(Bitmap src, double value) {
    // image size
    int width = src.getWidth();
    int height = src.getHeight();
    // create output bitmap
    Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
    // color information
    int A, R, G, B;
    int pixel;
    // get contrast value
    double contrast = Math.pow((100 + value) / 100, 2);

    // scan through all pixels
    for(int x = 0; x < width; ++x) {
        for(int y = 0; y < height; ++y) {
            // get pixel color
            pixel = src.getPixel(x, y);
            A = Color.alpha(pixel);
            // apply filter contrast for every channel R, G, B
            R = Color.red(pixel);
            R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
            if(R < 0) { R = 0; }
            else if(R > 255) { R = 255; }

            G = Color.red(pixel);
            G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
            if(G < 0) { G = 0; }
            else if(G > 255) { G = 255; }

            B = Color.red(pixel);
            B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
            if(B < 0) { B = 0; }
            else if(B > 255) { B = 255; }

            // set new pixel color to output bitmap
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }

    return bmOut;
}

Set the double value to 50 on mathod call. For Example createContrast(Bitmap src, 50)

在 mathod 调用中将 double 值设置为 50。例如createContrast(Bitmap src, 50)

回答by lenooh

Use the built-in methods:

使用内置方法:

public static Bitmap toGrayscale(Bitmap srcImage) {

    Bitmap bmpGrayscale = Bitmap.createBitmap(srcImage.getWidth(), srcImage.getHeight(), Bitmap.Config.ARGB_8888);

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

    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);
    paint.setColorFilter(new ColorMatrixColorFilter(cm));
    canvas.drawBitmap(srcImage, 0, 0, paint);

    return bmpGrayscale;
}