gpt4 book ai didi

Android - BitmapFactory.decodeByteArray 返回 null

转载 作者:行者123 更新时间:2023-11-29 18:20:04 33 4
gpt4 key购买 nike

我正在尝试使用套接字连接将图像从 pc 传输到 android。我能够从电脑接收数据到手机,但是当我将 byte[] 传递给 BitmapFactory 时,它返回 null。有时它会返回图像,但并非总是如此。

图像的大小是40054 字节。我一次接收 2048 字节,因此创建了保存 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,但结果是一样的。

知道我哪里做错了吗?

谢谢

最佳答案

我不知道这对你的情况是否有帮助,但通常你不应该依赖 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;
}
}

关于Android - BitmapFactory.decodeByteArray 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6002099/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com