方式一:通过改变图像的色相(Hue)、饱和度(saturation)和亮度(lum)都图像进行处理;
图像RGBA分析:
1. 色调/色相—物体传递的颜色
2. 饱和度—颜色的纯度,从0(灰)到100%(饱和)来描述
3. 亮度/明度—颜色的相对明暗程度
设置色调
ColorMatrix hueMatrix = new ColorMatrix();
hueMatrix.setRotate(0, hue); 0代表R
hueMatrix.setRotate(1, hue); 1代表G
hueMatrix.setRotate(2, hue); 2代表B
设置饱和度
ColorMatrix saturationMatrix = new ColorMatrix();
saturationMatrix.setSaturation(saturation);
设置亮度
ColorMatrix lumMatrix = new ColorMatrix();
lumMatrix.setScale(lum, lum, lum, 1);
使用postConcat()把三种设置组合在一起,画笔设置颜色过滤,并在画布上画出图像
ColorMatrix imageMatrix = new ColorMatrix();
imageMatrix.postConcat(hueMatrix);
imageMatrix.postConcat(saturationMatrix);
imageMatrix.postConcat(lumMatrix);
paint.setColorFilter(new ColorMatrixColorFilter(imageMatrix)); //设置画笔
canvas.drawBitmap(bm, 0, 0, paint); //在画布上画出原图
注意:进行图像处理前不可以在原图上面修改,要创建出一个新的Bitmap
Bitmap bmp = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);//创建一个跟原图大小一样的Bitmap
Canvas canvas = new Canvas(bmp);
实际上,上述设置色相、饱和度和亮度,查看源码后会发现,是通过下面矩阵的方法实现图像变化;
方式二:通过图像矩阵变换对图像进行处理
android用一个颜色值矩阵存放当前的RGBA值,与4*5颜色矩阵运算获得一个新的颜色值矩阵,通过这种方式对图像进行处理
运算结果:
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;
详细矩阵处理方式参考:文章地址
Bitmap bt=Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);
ColorMatrix colorMatrix=new ColorMatrix();//matrixdatas是一个长为4*5的数组,用来保存颜色矩阵
colorMatrix.set(matrixdatas);
Canvas canvas=new Canvas(bt);
Paint paint=new Paint();
paint.setAntiAlias(true);
paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
canvas.drawBitmap(bitmap,0,0,paint);
colorMatrixIV.setImageBitmap(bt);
方式三:通过图像的像素点对图像进行处理
一个完整的图像是由像素点构成的,可以通过改变图像的像素点,对图像进行处理;
int with=bm.getWidth();//图片的宽度,由于单位是px,也就是横向像素点的个数
int height=bm.getHeight();//图片的高度,由于单位是px,也就是纵向像素点的个数
int newPixs[]=new int[with*height];//保存处理后所有的像素点
int oldpixs[]=new int[with*height];//保存图像的所有像素点
int a,r,g,b;
int color;
Bitmap bt=Bitmap.createBitmap(with,height, Bitmap.Config.ARGB_8888);
bm.getPixels(oldpixs,0,with,0,0,with,height);//获取图片的所有像素点,保存在oldpixs中
for(int i=0;i<oldpixs.length;i++){
color=oldpixs[i];
r=Color.red(color); //获取像素点的R值
g=Color.green(color); //获取像素点的G值
b=Color.blue(color); //获取像素点的B值
a=Color.alpha(color); //获取像素点的A值
//对各个像素点机型操作
r = 255 - r;
g = 255 - g;
b = 255 - b;
if(r>255){
r=255;
}else if (r<0){
r=0;
}
if(g>255){
g=255;
}else if(g<0){
g=0;
}
if(b>255){
b=255;
}else if(b<0){
b=0;
}
newPixs[i]=Color.argb(a,r,g,b);//通过RGBA值获取新的像素点
}
bt.setPixels(newPixs,0,with,0,0,with,height);//设置像素点
如有错误,欢迎指出;