Java 通过套接字发送图像流问题-Android

Java 通过套接字发送图像流问题-Android,java,android,image,sockets,stream,Java,Android,Image,Sockets,Stream,我已经实现了一个应用程序,它使用SP摄像头拍摄照片,并通过套接字将照片发送到服务器 我使用以下代码读取本地存储的图像文件,并通过套接字连续发送它: FileInputStream fileInputStream = new FileInputStream( "my_image_file_path" ); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16

我已经实现了一个应用程序,它使用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();
}
我面临的问题是更改字节数组的大小
data[]
会影响实际发送到服务器的图像数量

下面发布的图片应该有助于您理解:

  • byte[]data=新字节[16384]

  • byte[]data=新字节[32768]

  • byte[]data=新字节[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();

您可以尝试在每次写入后向networkOutputStream添加刷新。另外,我不明白ByteArrayOutputStream是做什么的。最后,请确保正确关闭流。@brianestey-我只是没有发布有关流的
close()
函数的部分。我现在就试试看。你说得对,太多了!为了理解,为什么使用
ByteArrayOutputStream()
会产生这个问题?我认为buffer.flush()应该在networkOutputStream.write(buffer.toByteArray())之前@Matteo不,这是因为每次它增长时,你都会发送它的全部内容,而且从不清除它。