如何在Android中将彩色图像转换为黑白图像

10

我想知道在Android中,将从互联网上下载的彩色图像转换为黑白图像并显示给用户的方法。 您是否在您的Android工作中遇到过此需求?请告诉我。

谢谢 Lakshman

2个回答

10

使用内置方法:

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;
}

10

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

看看这段代码..

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;
}

在调用该方法时将double值设置为50。例如:createContrast(Bitmap src, 50)


6
太好了,它完美运行,但速度很慢。我正在将6个大小为300像素×300像素的JPEG图像在常规Android设备上转换,这需要6秒钟!除了缩小图像尺寸之外,我能做些什么来减少时间吗? - Alireza Ahmadi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接