1

ソケット接続を使用して PC から Android に画像を転送しようとしています。PC から電話にデータを受信できますが、byte[]toに渡すBitmapFactoryと 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たが、結果は同じでした。

私が間違っているところはありますか?

ありがとう

4

1 に答える 1

3

これがあなたの場合に役立つかどうかはわかりませんが、一般に、要求した正確なバイト数を読み取るためにInputStream.read(byte []、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;
    }
}
于 2011-05-14T16:45:08.827 に答える