android 图片转为bitmap,黑白镜过滤

图片转bitmap

1.获取图片资源

Bitmap bitmap= BlackWhite(BitmapFactory.decodeResource(getResources(), R.mipmap.test, null));

2.sd卡(要获取权限 文件和读写权限)

String fileName=Environment.getExternalStorageDirectory().getAbsolutePath()+"/tencent/MicroMsg/WeiXin/test.jpeg";

Bitmap bit = BitmapFactory.decodeFile(fileName);

下面是黑白镜过滤的方法

public static Bitmap BlackWhite(Bitmap bitmap) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    Bitmap resultBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
    int color = 0;
    int a, r, g, b, r1, g1, b1;
    int[] oldPx = new int[w * h];
    int[] newPx = new int[w * h];

    bitmap.getPixels(oldPx, 0, w, 0, 0, w, h);
    for (int i = 0; i < w * h; i++) {
        color = oldPx[i];

        r = Color.red(color);
        g = Color.green(color);
        b = Color.blue(color);
        a = Color.alpha(color);

        //黑白矩阵
        r1 = (int) (0.33 * r + 0.59 * g + 0.11 * b);
        g1 = (int) (0.33 * r + 0.59 * g + 0.11 * b);
        b1 = (int) (0.33 * r + 0.59 * g + 0.11 * b);

        //检查各像素值是否超出范围
        if (r1 > 255) {
            r1 = 255;
        }

        if (g1 > 255) {
            g1 = 255;
        }

        if (b1 > 255) {
            b1 = 255;
        }

        newPx[i] = Color.argb(a, r1, g1, b1);
    }
    resultBitmap.setPixels(newPx, 0, w, 0, 0, w, h);
    return resultBitmap;
}

下面这个方法也是可以的

 

public static Bitmap getGrayBitmap(Bitmap bm){
    Bitmap bitmap = null;
    //获取图片的宽和高
    int width = bm.getWidth();
    int height = bm.getHeight();
    //创建灰度图片
    bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    //创建画布
    Canvas canvas = new Canvas(bitmap);
    //创建画笔
    Paint paint = new Paint();
    //创建颜色矩阵
    ColorMatrix matrix = new ColorMatrix();
    //设置颜色矩阵的饱和度:0代表灰色,1表示原图
    matrix.setSaturation(0);
    //颜色过滤器
    ColorMatrixColorFilter cmcf = new ColorMatrixColorFilter(matrix);
    //设置画笔颜色过滤器
    paint.setColorFilter(cmcf);
    //画图
    canvas.drawBitmap(bm, 0,0, paint);
    return bitmap;
}

你可能感兴趣的:(移动开发)