Android踩坑指南之Bitmap:ARGB8888
下面是一个Android中通过BItMap show 一张argb图片的sample
private void writeTxtToFile(byte[] strcontent, String fileName) {
//生成文件夹之后,再生成文件,不然会出错
Log.d(TAG,"TwriteTxtToFile");
try {
File file = new File(this.getExternalFilesDir(
Environment.DIRECTORY_PICTURES)+"/data.raw");
if (!file.createNewFile()) {
Log.d(TAG, "Directory not created");
}
OutputStream out = new FileOutputStream(file);
out.write(strcontent);
} catch (Exception e) {
Log.e("TestFile", "Error on write File:" + e);
}
}
void showAvartar(byte[] picSrc) {
if(null == picSrc) {
Log.e(TAG, "showAvartar: picSrc is null");
return;
}
Log.d(TAG, "showAvartar: ");
Bitmap bitmap;
//Bitmap.createBitmap()
for(int i =0; i<128*72 ; i++) {
// Log.d(TAG, "R: " + Integer.toHexString(picSrc[0] & 0xff));
// Log.d(TAG, "G: " + Integer.toHexString(picSrc[0+1] & 0xff));
// Log.d(TAG, "B: " + Integer.toHexString(picSrc[0+2] & 0xff));
// Log.d(TAG, "A: " + Integer.toHexString(picSrc[0+3] & 0xff));
}
if (picSrc.length != 0) {
//toast(0,0,0,0,"AvatarData size:" + picSrc.length,"",null);
int[] imageData = new int[picSrc.length/4];
int j =0 ;
for(int i =0 ; i<128*72*4 ; i=i+4 )
{
imageData[j] = (picSrc[i+3] & 0xff) << 24 | (picSrc[i+2] & 0xff) << 16 | (picSrc[i+1] & 0xff) << 8 | (picSrc[i] & 0xff);
j++;
}
bitmap = Bitmap.createBitmap(imageData,128, 72, Bitmap.Config.ARGB_8888);
String fileName = "data.raw";
writeTxtToFile(picSrc,fileName);
if(bitmap != null){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
imageView.setImageBitmap(bitmap);
imageView.invalidate();
}
});
}else {
Log.e(TAG, "showAvartar: bitmap is null");
}
}else{
Log.d(TAG, "showAvartar: picSrc.length is 0");
}
}
ARGB8888 32位 一个像素4个字节
踩坑:
如API中所述:
int color = (A & 0xff) << 24 | (B & 0xff) << 16 | (G & 0xff) << 8 | (R & 0xff);
也就是说 实际BitMap中图片通道顺序是ABGR
补充
skia/opencv/jpeg 引擎中的像素与字节顺序
注意这里按字节送到接口中的图像字节数组顺序是BGRA
所以在使用接口前要注意其像素排列与字节数组的关系是否正确 避免踩坑