2012-04-17 99 views
46

我有一個位圖,我想發送到服務器,通過編碼到base64,但我不想壓縮在PNG或JPEG圖像。將位圖轉換爲byteArray android

現在我以前在做的是。

ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream(); 
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY, byteArrayBitmapStream); 
byte[] b = byteArrayBitmapStream.toByteArray(); 
//then simple encoding to base64 and off to server 
encodedImage = Base64.encodeToString(b, Base64.NO_WRAP); 

現在我只是不希望使用任何壓縮,也沒有任何形式樸素簡單的byte []從位圖,我可以編碼併發送到服務器。

任何指針?

回答

123

您可以使用copyPixelsToBuffer()將像素數據移動到Buffer,也可以使用getPixels(),然後使用位移將整數轉換爲字節。

copyPixelsToBuffer()可能是你要幹什麼用的,所以這裏是你如何使用它的一個例子:

//b is the Bitmap 

//calculate how many bytes our image consists of. 
int bytes = b.getByteCount(); 
//or we can calculate bytes this way. Use a different value than 4 if you don't use 32bit images. 
//int bytes = b.getWidth()*b.getHeight()*4; 

ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer 
b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer 

byte[] array = buffer.array(); //Get the underlying array containing the data. 
+2

小代碼會大大幫助:) – 2012-04-17 13:22:13

+1

byte [] b; \t \t \t \t ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapPicture.getByteCount()); \t \t bitmapPicture.copyPixelsToBuffer(byteBuffer); \t \t b = byteBuffer.array(); ??? – 2012-04-17 13:22:58

+0

@AsadKhan我添加了一個例子。 – Jave 2012-04-17 13:33:06

5

代替@jave回答以下行:

int bytes = b.getByteCount(); 

使用下面的線和功能:

int bytes = byteSizeOf(b); 

protected int byteSizeOf(Bitmap data) { 
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) { 
    return data.getRowBytes() * data.getHeight(); 
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { 
    return data.getByteCount(); 
} else { 
     return data.getAllocationByteCount(); 
} 
3
BitmapCompat.getAllocationByteCount(bitmap); 

有助於找到所需的字節緩衝區大小