1. 程式人生 > >Android之利用ColorMatrix進行圖片的各種特效處理

Android之利用ColorMatrix進行圖片的各種特效處理

原圖:效果1:效果2:

效果3:效果4:

檢視官方的API,其中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;

那這裡我簡單的理解為:

所謂的顏色矩陣其實就是一張點陣圖,那這個點陣圖是5*4的矩陣,這個矩陣涉及到顏色和透明度,按照以上的一個公式,我們可以將這個顏色矩陣繪製出來:

   a   b   c    d   e

   f    g   h    i    j

   k    l   m   n   o

   p    q   r   s    i

除了5*4的顏色矩陣外,我們還需要影象的RGBA的值,通過RGBA可以決定圖片顏色所呈現的效果,影象的RGBA的值儲存在一個5*1的顏色分量矩陣中,如下:

 R

 G

 B

 A

 1

如果我們要改變影象的顏色,可以通過改變影象的顏色分量矩陣就可以做到,關於顏色分量矩陣的計算公式如下:

   a   b   c    d   e         R         aR+bG+cB+dA+e

   f    g   h    i    j          G          fR+gG+hB+jA+j

                                *  B  =

   k    l   m   n   o          A         kR+IG+mB+nA+o

   p    q   r   s    i           1         pR+qG+rB+sA+i

因此以上第一行代表紅色成分,第二行代表綠色成分,第三行代表藍色成分,第四行代表透明度。

程式碼如下:

public class MainActivity extends Activity {
	private Button btn_start;
	private ImageView img;
	private Bitmap bitmap;
	private float[] colorArray = {  1, 0, 0, 0, 0,
					0, 1, 0, 0, 1,
					2, 0, 1, 0, 0,
				0, 0, 0, 1, 0 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_layout);
		initView();
	}

	private void initView() {
		img = (ImageView) findViewById(R.id.iv_image);
		bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();

		btn_start = (Button) findViewById(R.id.btn_start);
		btn_start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bitmap bm = ImageTools.toProcessImage(bitmap,colorArray);
				img.setImageBitmap(bm);
			}
		});

	}
}


ImageTools工具類:

/**
	 * 圖片特效處理
	 * @param bmp  傳入的圖片
	 * @param colorArray 顏色矩陣值 
	 * @return
	 */
	public static Bitmap toProcessImage(Bitmap bmp,float[] colorArray){
		if(bmp!=null&&colorArray!=null){
			int width, height;
			height = bmp.getHeight();
			width = bmp.getWidth();
			Bitmap bm = Bitmap.createBitmap(width, height,
					Bitmap.Config.RGB_565);
			Paint myPaint = new Paint(); 
			Canvas canvas=new Canvas(bm);               
	        ColorMatrix myColorMatrix = new ColorMatrix(); 
	        myColorMatrix.set(colorArray);
	        myPaint.setColorFilter(new ColorMatrixColorFilter(myColorMatrix));     
	        canvas.drawBitmap(bmp,0,0,myPaint);  
	        return bm;
		}else{
			return bmp;
		}
		
	}