我搜索了又搜索,发现的一切都很有帮助,但我总是出现内存不足的错误。我发送的图像是.06 MB,所以我知道问题不在于将字节[]解码为位图。当我删除while循环时,这就像一帧的魅力,但我想要多帧。我正在获取一个字节[],并使用套接字将其发送到另一个设备,但我不知道如何做到这一点。我的问题是我没有发送和接收正确的byte[]长度。这就是我目前正在做的事情。
while (count != -1) {
//first send the byte[] length
dataOutputStream.writeInt(sendPackage.length);
//pass a byte array
publishProgress("sending file to client");
showMyToastOnUiThread(String.valueOf(sendPackage.length));
outputStream.write(sendPackage, 0, sendPackage.length);
outputStream.flush();
}
在不同设备上接收字节[]:
int count = inputStream.read();
while (count != -1) {
int byteArrayLength = dataInputStream.readInt();
Log.i(MainActivity.TAG, "Starting convert to byte array");
byte[] receivedBytes = convertInputStreamToByteArray(inputStream, byteArrayLength);
Bitmap bitmap = BitmapFactory.decodeByteArray(receivedBytes, 0, receivedBytes.length);
publishProgress(bitmap);
}
//convert inputstream to byte[]
public byte[] convertInputStreamToByteArray(InputStream inputStream, int readLength) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[readLength];
try {
Log.i(MainActivity.TAG, "Starting convert to byte array while loop");
int readTotal = 0;
int count = 0;
while (count >= 0 && readTotal < readLength) {
count = inputStream.read(data, readTotal, readLength - readTotal);
if (readLength > 0) {
readTotal += count;
}
}
Log.i(MainActivity.TAG, "Finished convert to byte array while loop");
} catch (IOException e) {
Log.e(MainActivity.TAG, "error: " + e.getMessage());
e.printStackTrace();
}
return data;
}
这就是问题所在:
int count = inputStream.read();
while (count != -1) {
你正在消耗一个字节,然后忽略它。这意味着你读取的下一个值(大小)将不正确。你需要一种不同的方式来判断你是否处于流的末尾。一些选项:
- 完成后发送-1;这样一来,一旦
readInt
返回-1,您就可以停止 - 如果你知道,在开始发送之前先发送要发送的图像数量
- 如果流支持标记,请使用
mark(1)
、read()
和reset()
。我不知道会不会。如果不是的话,你总是可以用BufferedInputStream
来包装它 - 您自己重新实现
DataInputStream.readInt
,将流的末尾检测为预期的可能性,而不是抛出异常 - 只需在
readInt
中捕获一个异常(这并不好——到达流的末尾并不是什么异常)