讀取Bitmap Pixel ARGB (Alpha,red,green,blue),
並且轉換為灰階 (灰階公式: gray = (r*0.299 + g*0.587 + b*0.114))
相較於 bitmap 的 getPixels() 函式快了許多!!
程式碼:
public static Bitmap toGray(Bitmap src){
int bmWidth = src.getWidth();
int bmHeight = src.getHeight();
int[] newBitmap = new int[bmWidth * bmHeight];
src.getPixels(newBitmap, 0, bmWidth, 0, 0, bmWidth, bmHeight);
for (int h = 0; h < bmHeight; h++){
for (int w = 0; w < bmWidth; w++){
int index = h * bmWidth + w;
int a = (newBitmap[index] >> 24) & 0xff;//讀取Alpha
int r = (newBitmap[index] >> 16) & 0xff;//讀取red
int g = (newBitmap[index] >> 8) & 0xff;//讀取green
int b = newBitmap[index] & 0xff;//讀取blue
int gray = (int)(r*0.299 + g*0.587 + b*0.114) ;
r = gray;
g = gray;
b = gray;
newBitmap[index] = (a << 24) | (r << 16) | (g << 8) | b;
}
}
Bitmap mBmp = Bitmap.createBitmap(bmWidth, bmHeight, Bitmap.Config.ARGB_8888);
mBmp.setPixels(newBitmap, 0, bmWidth, 0, 0, bmWidth, bmHeight);
return mBmp;
}
沒有留言:
張貼留言