相信大家都用过美图秀秀、美颜相机app吧,其实是对图片修改,实现的原理也就是重写对图片RGB颜色重新的编写和计算来达到实现另外的效果。
为了便于大家对滤镜算法的学习,写得不好的地方大家请见谅,有些网友说代码能看懂,但是里面的某些数值不知道是怎么计算出来的,说实话有些数值我不查资料我也不是很清楚,但是当我需要知道的时候我也会慢慢查阅算法的核心思想,很多参数由此而来。同时也希望大家养成不懂就查的习惯。
废话就不多说了直接上代码:
image1为原来的图片 image2为修改以后的图片
private ImageView mImage1;
private ImageView mImage2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mImage1 = (ImageView) findViewById(R.id.image1);
mImage2 = (ImageView) findViewById(R.id.image2);
//本地Res.mipmap.image转成Bitmap
Resources res = MainActivity.this.getResources();
Bitmap bmp= BitmapFactory.decodeResource(res, R.mipmap.image);
mImage1.setImageBitmap(bmp);
mImage2.setImageBitmap(GrayFilter.changeToGray(bmp));
}
这是Activity的代码
下面是图片修改的代码:
里面有些算法是查阅各种资料搜集到的,还不算完整大家先这样用吧
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 = //ColorMatrix matrix = new ColorMatrix(new float[]{
{1.25f, 0, 0, 0, 0, //-1, 0, 0, 0, 255,
0, 1.25f, 0, 0, 0, //0, -1, 0, 0, 255,
0, 0, 1.25f, 0, 0, // 0, 0, -1, 0, 255,
0, 0, 0, 1.25f, 0}; //0, 0, 0, 1, 0,
/**
*图像为灰色 //紫色
* float[] array ={ ColorMatrix matrix = new ColorMatrix(new float[]{
0.3f, 0.59f, 0.11f, 0, 0, 0, 1f, 0, 0, 0,
0.3f, 0.59f, 0.11f, 0, 0, 1f, 0, 0, 0, 0,
0.3f, 0.59f, 0.11f, 0, 0, 0, 0, 1f, 0, 0,
0, 0, 0, 1, 0 } 0, 0, 0, 1f, 0,});
*/
/*
* 黑白图片 //复古风格
* ColorMatrix matrix = new ColorMatrix(new float[]{ ColorMatrix matrix = new ColorMatrix(new float[]{
0.213f, 0.715f, 0.072f, 0, 0, 1/2f,1/2f,1/2f,0,0,
0.213f, 0.715f, 0.072f, 0, 0, 1/3f,1/3f,1/3f,0,0,
0.213f, 0.715f, 0.072f, 0, 0, 1/4f,1/4f,1/4f,0,0,
0, 0, 0, 1f, 0, 0,0,0,1f,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;
}
这个代码可能复制出去有点问题,没有问题最好,我也没有试,希望大家能够用到吧。