android - 如何以编程方式更改 android 中位图的对比度?

标签 android image-processing bitmap contrast

我想以编程方式更改位图的对比度。到现在我都试过了。

private Bitmap adjustedContrast(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.green(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.blue(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;
    }

但这并没有按预期工作。请帮助我或提供任何其他解决方案来实现这一目标。提前致谢。

最佳答案

这里是完整的方法:

/**
 * 
 * @param bmp input bitmap
 * @param contrast 0..10 1 is default
 * @param brightness -255..255 0 is default
 * @return new bitmap
 */
public static Bitmap changeBitmapContrastBrightness(Bitmap bmp, float contrast, float brightness)
{
    ColorMatrix cm = new ColorMatrix(new float[]
            {
                contrast, 0, 0, 0, brightness,
                0, contrast, 0, 0, brightness,
                0, 0, contrast, 0, brightness,
                0, 0, 0, 1, 0
            });

    Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());

    Canvas canvas = new Canvas(ret);

    Paint paint = new Paint();
    paint.setColorFilter(new ColorMatrixColorFilter(cm));
    canvas.drawBitmap(bmp, 0, 0, paint);

    return ret;
}

关于android - 如何以编程方式更改 android 中位图的对比度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12891520/

相关文章:

android - Android EditText 的控制键盘类型(仅限数字)

OpenCV圆畸变检测

java - 白色背景上图像的边缘检测

android - 翻译用于绘制位图的矩阵时,它会绘制多个位图

c - 跳过位图到字符串转换器中的填充?

android - Ionic/Cordova Web App - 启动时出现 index.html 错误

android - Android 上的 NativeScript (Telerik) 和串口

java - 将弹出窗口中的 EditText 设置为等于先前 Activity 的字符串 - 错误 :(92, 30) 错误:不兼容的类型: double 无法转换为字符串

python - 在 QLabel 中渲染 WSQ 图像的最佳方式是什么

android - 将字符串文本转换为位图