Android知识点|史上最全的Android 图片滤镜 colorMatrix自定义任意图片滤镜

先看效果图










源码下载: https://github.com/qiushi123/BlurBehindActivity





对图像进行颜色方面的处理,通过使用颜色矩阵(ColorMatrix)来实现。从而可以达到很多特效如黑白老照片、泛黄旧照片等等。


颜色矩阵(ColorMatrix)实现滤镜效果
一,知识简介
一张位图可以转换为一个5*4的矩阵,涉及到颜色和透明度。如图1所示。在Android中,
颜色矩阵M是以一维数组m=[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t]的方式进行存储的。
在一张图片中,图像的RGBA(红色、绿色、蓝色、透明度)值决定了该图片所呈现出来的颜色效果。
要想改变一张图片的颜色效果,只需要改变图像的颜色分量矩阵即可。通过颜色矩阵可以很方便的修改图像的颜色分量矩阵。
由此可见,通过颜色矩阵修改了原图像的RGBA值,从而达到了改变图片颜色效果的目的。
并且,通过如图3所示的运算可知,颜色矩阵M的
第一行参数abcde决定了图像的红色成分,
第二行参数fghij决定了图像的绿色成分,
第三行参数klmno决定了图像的蓝色成分,
第四行参数pqrst决定了图像的透明度,
第五列参数ejot是颜色的偏移量。

通常,改变颜色分量时可以通过修改第5列的颜色偏移量来实现,
如图4所示的颜色矩阵M1,通过计算后可以得知该颜色矩阵的作用是使图像的红色分量和绿色分量均增加100,
这样的效果就是图片泛黄(因为红色与绿色混合后得到黄色)。


二,以黑白效果为例(有两种实现方法)
1,用数组矩阵
float[] array = {1, 0, 0, 0, 100,
0, 1, 0, 0, 100,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0};
ColorMatrix colorMatrix = new ColorMatrix(array);
2,把饱和度设置为0 就可以得到黑白的图片
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);



====================实例代码========================================
package com.huxiu.yd.api.lib.filterAPI;


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;


public class GrayFilter {
// 黑白效果函数
public static Bitmap changeToGray(Bitmap bitmap) {


int width, height;
width = bitmap.getWidth();
height = bitmap.getHeight();


Bitmap grayBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(grayBitmap);
Paint paint = new Paint();
paint.setAntiAlias(true); // 设置抗锯齿


//一,数组矩阵的方法

/*float[] array = {1, 0, 0, 0, 100,
0, 1, 0, 0, 100,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0};
ColorMatrix colorMatrix = new ColorMatrix(array);
*/


//二,把饱和度设置为0 就可以得到灰色(黑白)的图片
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);


ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);


paint.setColorFilter(filter);
canvas.drawBitmap(bitmap, 0, 0, paint);


return grayBitmap;
}
}


3,上面实例代码的使用(传入bitmap即可添加滤镜后的效果)
Bitmap newBitmap = GrayFilter.changeToGray(bitmap);

//把添加滤镜后的效果显示在imageview上
imageview.setBackground(new BitmapDrawable(getResources(), newBitmap));



三,常用的颜色矩阵
1,宝丽来彩色[Polaroid Color]

float[] array = {1.438, -0.062, -0.062, 0, 0,
-0.122, 1.378, -0.122, 0, 0,
-0.016, -0.016, 1.483, 0, 0,
-0.03, 0.05, -0.02, 1, 0};
ColorMatrix colorMatrix = new ColorMatrix(array);

2,怀旧效果
float[] array = {0.393f,0.769f,0.189f,0,0,
0.349f,0.686f,0.168f,0,0,
0.272f,0.534f,0.131f,0,0,
0,0,0,1,0};
ColorMatrix colorMatrix = new ColorMatrix(array);

3,泛红
2,0,0,0,0,
0,1,0,0,0,
0,0,1,0,0,
0,0,0,1,0
4,泛绿(荧光绿)
1,0,0,0,0,
0,1.4,0,0,0,
0,0,1,0,0,
0,0,0,1,0
5,泛蓝(宝石蓝)
1,0,0,0,0,
0,1,0,0,0,
0,0,1.6,0,0,
0,0,0,1,0
6,泛黄(把红色 跟绿色分量都加50)
1,0,0,0,50,
0,1,0,0,50,
0,0,1,0,0,
0,0,0,1,0



演示apk

http://download.csdn.net/detail/qiushi_1990/9434300
【Android知识点|史上最全的Android 图片滤镜 colorMatrix自定义任意图片滤镜】




    推荐阅读