秋梦无痕

一场秋雨无梦痕,春夜清风冻煞人。冬来冷水寒似铁,夏至京北蟑满城。

Avatar

使用ColorMatrix转换图片

Android下把一个图片显示为灰度(GrayScale),或者反色(Invert),怎么做呢?

首先来看ColorMatrix文档:

5x4 matrix for transforming the color+alpha components of a Bitmap. The matrix is stored in a single array, and its treated as follows: [ a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t ] When applied to a color [r, g, b, a], the resulting color is computed as (after clamping) R' = a*R + b*G + c*B + d*A + e; G' = f*R + g*G + h*B + i*A + j; B' = k*R + l*G + m*B + n*A + o; A' = p*R + q*G + r*B + s*A + t;


然后,我们有两个matrix:
float grayscale[] = {
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f
};
float invert[] = {
-1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f
};

示例代码:
// 获取新的Drawable的方法
float matrix[] = grayscale;
Drawable drawable = new BitmapDrawable(getResources(), bmpOriginal);
drawable.setBounds(0, 0, width, height);
drawable.mutate();
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(cf);
return drawable;

// 生成新的Bitmap的方法,同时灰度和反色
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);//设置为灰度,等同于 cm.set(grayscale) 或者 cm = new ColorMatrix(grayscale)
cm.postConcat(new ColorMatrix(invert)); // 反色
// 这里通过 cm.getArray() 输出可以得到合并之后的 matrix
// 由于我需要有选择的进行反色,所以没有合并,而且运算复杂程度应该一致
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;