我已经实现了一个使用 SP 相机拍照并通过套接字将其发送到服务器的应用程序。
我正在使用以下代码读取本地存储的图像文件并通过套接字以连续的 block 形式发送它:
FileInputStream fileInputStream = new FileInputStream( "my_image_file_path" );
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
try {
while( (nRead = fileInputStream.read(data, 0, data.length)) != -1 ){
buffer.write(data, 0, nRead);
networkOutputStream.write( buffer.toByteArray() );
buffer.flush();
}
} catch( IOException e ){
e.printStackTrace();
}
我面临的问题是,更改字节数组的大小 data[]
会影响实际发送到服务器的图像量。
下面张贴的图片应该可以帮助您理解:
byte[] data = new byte[16384];
byte[] data = new byte[32768];
byte[] data = new byte[65536];
等等。
如您所想,我可以找到一个允许我发送完整图像的尺寸,但这种临时解决方案是 Not Acceptable ,因为可能需要发送任何尺寸的图像。
我认为我以缓冲方式读取图像文件的方式似乎有问题,你能帮我吗?
提前致谢!
最佳答案
ByteArrayOutputStream 的使用是多余的,每次它增长时您都在发送它的全部内容。按如下方式更改循环:
FileInputStream fileInputStream = new FileInputStream( "my_image_file_path" );
int nRead;
byte[] data = new byte[16384];
try {
while( (nRead = fileInputStream.read(data)) != -1 ){
networkOutputStream.write( data, 0, nRead );
}
} catch( IOException e ){
e.printStackTrace();
}
fileInputStream.close();
关于java - 通过套接字发送图像流问题 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12058453/