public void getPixels(int[] pixels, int offset, int stride,int x, int y, int width, int height)
獲取原Bitmap的像素值存儲到pixels數組中。
參數:
pixels 接收位圖顏色值的數組
offset 寫入到pixels[]中的第一個像素索引值
stride pixels[]中的行間距個數值(必須大於等於位圖寬度)。不能為負數
x 從位圖中讀取的第一個像素的x坐標值。
y 從位圖中讀取的第一個像素的y坐標值
width 從每一行中讀取的像素寬度
height 讀取的行數
@Override
public Bitmap process(Bitmap bitmap) {
// TODO Auto-generated method stub
Bitmap destImage = Bitmap.createBitmap(400,
400, Config.ARGB_8888);
int width = destImage.getWidth();
int height = destImage.getHeight();
for(int i = 0; i < width/2; i++){
for(int j = 0; j < height/2; j++){
destImage.setPixel(i, j, Color.RED);//左上區域紅色
}
for(int j = height / 2; j < height; j++){
destImage.setPixel(i, j, Color.CYAN);//左下區域青色
}
}
for(int i = width / 2; i < width; i++){
for(int j = 0; j < height/2; j++){
destImage.setPixel(i, j, Color.YELLOW);//右上區域黃色
}
for(int j = height / 2; j < height; j++){
destImage.setPixel(i, j, Color.BLACK);//右下區域黑色
}
}//上述代碼確定了原圖destImage的所有像素值
int[] mPixels = new int[width * height];
for(int i = 0; i < mPixels.length; i++){
mPixels[i] = Color.BLUE;//數組中默認值為藍色
}
destImage.getPixels(mPixels, 0, width, 0, 0,
width, height);
Bitmap mResultBitmap = Bitmap.createBitmap(mPixels, 0, width, width, height,
Bitmap.Config.ARGB_8888);
return mResultBitmap;
}
原始destImage為四色的。
提取紅色區域:
destImage.getPixels(mPixels, 0, width, 0, 0, width/2, height/2);

提取黃色區域:
destImage.getPixels(mPixels, 0, width, width/2, 0, width/2, height/2);

提取青色區域:
destImage.getPixels(mPixels, 0, width, 0, height/2, width/2, height/2);

提取黑色區域:
destImage.getPixels(mPixels, 0, width, width/2, height/2, width/2, height/2);

從上面四個操作可以理解了x,y,width,height四個參數是如何控制提取原圖哪塊區域位置的元素的。上面這些有兩點需要說明:
1. 剩余的區域並不是透明的或空白的,因為mPixels數組的默認值為藍色,且新生成的bitmap的寬高值也是按原圖大小設定的。如果只需要提取之后的圖,那么只需要設置mPixels數組大小為提取的區域的像素數目,新生成的bitmap寬高依照提取區域設置即可。
2. 所有提取的區域都在新圖的左上角。這是因為提取的區域在mPixels中是從0位置存儲的。也就是新圖完全由提取之后的mPixels數組決定。offset參數則決定了新提取的元素存儲在mPixels數組中的起始位置。這一點需要明白提取像素是一行一行的存儲到mPixels數組中的。所以有如下結果:
提取區域在新圖區域左上角:offset = 0;
提取區域在新圖區域右上角:offset = width/2;
提取區域在新圖區域左下角:offset = width * (height / 2);
提取區域在新圖區域右下角:offset = width * (height / 2) + width / 2;
上面的這四個賦值同時也說明了提取的元素在mPixels這一二維數組中是呈塊狀區域存儲的,用二維圖來看比較清晰。我們只需要設定起始的元素的存儲位置offset即可。
stride是什么意思呢?它的值必須大於等於原圖的寬。通過實際應用來理解它:把兩張上述的四色圖拼接到一起
destImage.getPixels(mPixels, 0 , 2 * width, 0, 0, width, height); destImage.getPixels(mPixels, width , 2 * width, 0, 0, width, height); Bitmap mResultBitmap = Bitmap.createBitmap(mPixels, 0, width * 2, width * 2, height * 2, Bitmap.Config.ARGB_8888);

createBitmap和getPixels中的stride參數的意義是一樣的,正是通過這一參數實現了如何把塊狀區域在二維數組mPixels中也是塊狀區域的。
這個參數的意義是行間距,也即一行讀取完畢后,下一行應該間隔多少讀取,數組應該間隔多少才開始存儲下一行數據。
