钢镚儿冲刺一周期第三天
一、说在前面
昨天完成并实现了对图片像素的褪色处理,但是效率不高,今天打算在网上通过学习来实现算法的优化。、
二、大体思路
由于自己的想法实现起来效率并不高,所以今天要通过在网上寻找相似的案例来尝试学习。
三、代码
public class MainActivity extends Activity implements OnClickListener { private Button but_old = null; private Button but_func = null; private ImageView iv_show = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.picture_tuise); @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_one: func(); break; case R.id.btn_two: iv_show.setImageResource(R.drawable.f); break; } } //褪色处理 public void func() { Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.f); int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap base = Bitmap.createBitmap(width, height,bitmap.getConfig()); // Bitmap B=toGrayscale(base); Canvas canvas = new Canvas(base);//以base为模板创建canvas对象 canvas.drawBitmap(bitmap, new Matrix(),new Paint()); for(int i = 0; i < width; i++)//遍历像素点 { for(int j = 0; j < height*0.5; j++) { int color = bitmap.getPixel(i, j); int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); int a = Color.alpha(color); int avg = (r+g+b)/3;//RGB均值 if(avg >= 150)//100可以理解为经验值 { base.setPixel(i, j,Color.argb(a, 255, 255, 255));//设为白色 } else { base.setPixel(i, j,Color.argb(a, 0, 0, 0));//设为黑色 } } } bitmap.recycle(); iv_show.setImageBitmap(base); } //理想优化(未完成) public static Bitmap toGrayscale (Bitmap bmpOriginal) { int width, height; height = bmpOriginal.getHeight(); width = bmpOriginal.getWidth(); Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas c = new Canvas(bmpGrayscale); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bmpOriginal, 0, 0, paint); return bmpGrayscale; } }