2011-05-14 137 views
1

我想通過套接字連接將圖像從pc傳輸到android。我能夠從PC接收數據到手機,但是當我通過byte[]BitmapFactory時,它返回空。也有時它是返回圖像,但並不總是。Android - BitmapFactory.decodeByteArray返回null

圖片尺寸爲40054 bytes。我一次收到2048 bytes,因此創建了包含byte數據的小數據池(緩衝區)。收到完整的數據後,我將它傳遞給BitmapFactory。這裏是我的代碼:

byte[] buffer = new byte[40054]; 
byte[] temp2kBuffer = new byte[2048]; 
int buffCounter = 0; 
for(buffCounter = 0; buffCounter < 19; buffCounter++) 
{ 
    inp.read(temp2kBuffer,0,2048); // this is the input stream of socket 
    for(int j = 0; j < 2048; j++) 
    { 
     buffer[(buffCounter*2048)+j] = temp2kBuffer[j]; 
    } 
} 
byte[] lastPacket=new byte[1142]; 
inp.read(lastPacket,0,1142); 
buffCounter = buffCounter-1; 
for(int j = 0; j < 1142; j++) 
{ 
    buffer[(buffCounter*2048)+j] = lastPacket[j]; 
} 
bmp=BitmapFactory.decodeByteArray(buffer,0,dataLength); // here bmp is null 

計算

[19 data buffers of 2kb each] 19 X 2048 = 38912 bytes 
[Last data buffer] 1142 bytes 
38912 + 1142 = 40054 bytes [size of image] 

我也試圖在同一時間閱讀完整的40054個字節,但是這也沒有奏效。這裏是代碼:

inp.read(buffer,0,40054); 
bmp=BitmapFactory.decodeByteArray(buffer,0,dataLength); // here bmp is null 

最後檢查與decodeStream但結果是相同的。

任何想法,我做錯了?

感謝

回答

3

我不知道如果這能幫助你的情況,但總的來說,你不應該依賴於InputStream.read(字節[],INT,INT)來讀取你問的確切字節數對於。這只是最大的價值。如果您檢查InputStream.read文檔,您可以看到它返回您應該考慮的實際閱讀字節數。

通常,當從InputStream中加載所有數據,並希望在讀取所有數據時關閉它,我會這樣做。

ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream(); 
int readLength; 
byte buffer[] = new byte[1024]; 
while ((readLength = is.read(buffer)) != -1) { 
    dataBuffer.write(buffer, 0, readLength); 
} 
byte[] data = dataBuffer.toByteArray(); 

如果你有隻加載一定量的數據,你知道的事先大小。

byte[] data = new byte[SIZE]; 
int readTotal = 0; 
int readLength = 0; 
while (readLength >= 0 && readTotal < SIZE) { 
    readLength = is.read(data, readTotal, SIZE - readTotal); 
    if (readLength > 0) { 
     readTotal += readLength; 
    } 
} 
+0

看起來有幫助...讓我檢查一下......謝謝! – 2011-05-15 07:34:01

相關問題