2016-07-28 22 views
2

我通過socket接收jpg圖片和我在做什麼是它被作爲字節緩衝區 :如何的ByteBuffer轉換爲圖像中的Android

 ByteBuffer receivedData ; 
     // Image bytes 
     byte[] imageBytes = new byte[0]; 
     // fill in received data buffer with data 
     receivedData= DecodeData.mReceivingBuffer; 
     // Convert ByteByffer into bytes 
     imageBytes = receivedData.array(); 
     ////////////// 
     // Show image 
     ////////////// 
     final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length); 
     showImage(bitmap1); 

但正在發生的事情,它未能在imageBytes解碼和位圖爲空。

另外我imagebytes爲: imageBytes:{-1,-40,-1,-32,0,16,74,70,73,70,0,1,1,1,0,96, 0,0,0,-1,-37,0,40,28,30,35,+10,478更多}

會是什麼問題? 是解碼問題嗎? 或從ByteBuffer到Byte數組的轉換?

在此先感謝您的幫助。

+0

'它被作爲ByteBuffer'。不要這樣想。它作爲字節流發送。 – greenapps

+0

'DecodeData.mReceivingBuffer'。你沒有說明你是如何收到這些數據的。代碼非常不完整。請顯示接收字節的十六進制表示法。請發送十六進制字節。 – greenapps

回答

2
ByteBuffer buf = DecodeData.mReceivingBuffer; 
byte[] imageBytes= new byte[buf.remaining()]; 
buf.get(imageBytes); 
final Bitmap bmp=BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length); 
    showImage(bmp); 

OR

// Create a byte array 
 
byte[] bytes = new byte[10]; 
 

 
// Wrap a byte array into a buffer 
 
ByteBuffer buf = ByteBuffer.wrap(bytes); 
 

 
// Retrieve bytes between the position and limit 
 
// (see Putting Bytes into a ByteBuffer) 
 
bytes = new byte[buf.remaining()]; 
 

 
// transfer bytes from this buffer into the given destination array 
 
buf.get(bytes, 0, bytes.length); 
 

 
// Retrieve all bytes in the buffer 
 
buf.clear(); 
 
bytes = new byte[buf.capacity()]; 
 

 
// transfer bytes from this buffer into the given destination array 
 
buf.get(bytes, 0, bytes.length); 
 

 
final Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length); 
 
showImage(bmp);

使用任何一塊上面來CONVERT TO字節緩衝區的字節數組並將其轉換爲位圖和SET到您的ImageView的。

希望這會幫助你。

+0

只是代碼沒有任何進一步的解釋是不是很有幫助。 – Robert

+0

它不能使用buf.get(imageBytes);不要用數據填充imagebytes我認爲imageBytes = receivedData.array();是更好,現在它解碼,但也不能顯示,但謝謝 – zelf

+0

@Andolaso​​ft感謝您的幫助,我認爲首先解決方案與更改buf.get(imageBytes);到buf.array將工作,因爲buf.get()在這兩個解決方案中沒有在imageBytes中寫任何東西。 – zelf

2

這一個工作,我(對ARGB_8888像素緩衝區):

private Bitmap getBitmap(Buffer buffer, int width, int height) { 
    buffer.rewind(); 
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
    bitmap.copyPixelsFromBuffer(buffer); 
    return bitmap; 
} 
相關問題