开发者

Android - BitmapFactory.decodeByteArray returns null

I am trying to transfer an image from pc to android using socket connection. I am able to receive the data from pc to phone but when I pass the byte[] to BitmapFactory, it is returning null. Also sometime it is returning image but not always.

The size of image is 40054 bytes. I am receiving 2048 bytes at a time so creating small data pool (buffer) which holds开发者_运维技巧 the byte data. After receiving full data, I am passing it to BitmapFactory. Here is my code:

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

Calculations

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

I have also tried to read full 40054 bytes at a time but this also didn't worked. Here is the code:

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

Also at last checked with decodeStream but the result was same.

Any idea where I am doing wrong?

Thanks


I don't know if this helps in your case but in general you shouldn't rely on InputStream.read(byte[], int, int) to read the exact number of bytes you ask for. It's maximum value only. If you check InputStream.read documentation you can see that it returns actual number of bytes read you should take into account.

Usually when loading all data from InputStream, and expect it to be closed once all data is read, I do something like this.

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();

And if you have to load only certain amount of data you know the size of beforehand.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜