2011-11-25 80 views
6

我通過藍牙以編程方式發送圖像。當我發送圖像作爲字節數組在發送端的字節數組長度是= 83402和在接收端我得到的1024字節bacthes。Android字節數組批量

我想將這1024個批次組合成單字節數組,使我再次將其轉換爲圖像。

在這裏msg.obj我得到1024字節數組的bacth。

情況下MESSAGE_READ:

byte[] readBuf = (byte[]) msg.obj; 

Bitmap bmp=BitmapFactory.decodeByteArray(readBuf,0,readBuf.length); 

在那之後我也收到這樣的警告。在的BufferedOutputStream構造函數中使用

「默認緩衝區大小是否需要8K的緩衝區,將是更好的是明確的。 「

任何幫助,將不勝感激。

感謝

回答

1

應該大致是這樣的:

byte[] readBuf = new byte[83402]; // this array will hold the bytes for the image, this value better be not hardcoded in your code 

int start = 0; 
while(/*read 1024 byte packets...*/) { 
    readBuf.copyOfRange((byte[]) msg.obj, start, start + 1024); // copy received 1024 bytes 
    start += 1024; //increment so that we don't overwrite previous bytes 
} 

/*After everything is read...*/ 
Bitmap bmp=BitmapFactory.decodeByteArray(readBuf,0,readBuf.length); 
0

我要去這裏走出去的肢體,並假設你正在使用的BluetoothChat example從SDK構建的圖像發送(所有的例子都符合它)。以下是我扔在一起的快速轉換 - 可能不是最好的,但它的工作原理。

由於在BluetoothChatService.java運行函數中它創建了緩衝區數組大小爲1024的緩衝區數組,並且從輸入流獲取信息,因此您可以批量獲取它們。如果你創建另一個緩衝區,將適合的圖像那裏(我設定的最高1MB),那麼你運行功能將有:

byte[] buffer = new byte[1024]; 
byte[] imgBuffer = new byte[1024*1024]; 
int pos = 0; 

與你在你的imgBuffer其中您的POS變量保持跟蹤。

然後你只要複製過來當你在這樣的圖像的同時(true)循環獲取塊(mmInStream是一個InputStream):

int bytes = mmInStream.read(buffer); 
System.arraycopy(buffer,0,imgBuffer,pos,bytes); 
pos += bytes; 

我發送消息,讓它知道該圖像是完成了發送和在這一點上穿梭imgBuff給其他線程(POS擁有imgBuffer的尺寸在這一點上):

mHandler.obtainMessage(BluetoothChat.IMAGE_READ, pos, -1, imgBuffer) 
         .sendToTarget(); 

我已經定義IMAGE_READ到陣列就像你在做解碼您的MESSAGE_READ: