Mat*_*teo 4 java sockets android image stream
我已经实现了一个应用程序,它使用SP摄像头拍照并通过套接字将其发送到服务器.
我正在使用以下代码来读取本地存储的图像文件,并通过套接字以连续的块发送它:
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();
}
Run Code Online (Sandbox Code Playgroud)
我面临的问题是更改字节数组的大小data[]会影响实际发送到服务器的图像数量.
下面张贴的图片可以帮助您了解:
byte[] data = new byte[16384];
byte[] data = new byte[32768];
byte[] data = new byte[65536];
等等.
您可以想象我可以找到允许我发送完整图像的大小,但是这种临时解决方案是不可接受的,因为可能需要发送任何维度的图像.
在我看来,我以缓冲的方式阅读图像文件的方式似乎有问题,你能帮助我吗?
提前致谢!
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();
Run Code Online (Sandbox Code Playgroud)