简体   繁体   English

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

[英]Sending Image Stream over Socket Issue - Android

I've implemented an application that takes a picture with the SP camera and sends it over a socket to the server. 我已经实现了一个应用程序,该应用程序使用SP相机拍摄照片并将其通过套接字发送到服务器。

I'm using the following code to read the image file stored locally and send it in successive chunks over the socket: 我正在使用以下代码来读取本地存储的图像文件,并将其以连续的块形式通过套接字发送:

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();
}

The issue I'm facing is that changing the size of the array of bytes data[] affects how much of the image is actually sent to the server . 我面临的问题是, 更改字节data[]数组data[]的大小会影响实际发送到服务器的图像数量

The images posted below should help you understand: 下面发布的图像应该可以帮助您理解:

  • byte[] data = new byte[16384];

在此处输入图片说明

  • byte[] data = new byte[32768];

在此处输入图片说明

  • byte[] data = new byte[65536];

在此处输入图片说明

And so on. 等等。

As you can imagine I can find a size that allows me to send the full image, but such ad hoc solution is not acceptable since images of any dimension could need to be sent. 可以想象,我可以找到一个可以发送完整图像的尺寸,但是这种特殊的解决方案是不可接受的,因为可能需要发送任何尺寸的图像。

In my opinion there seems to be a problem in the way I am reading the image file in a buffered way, can you help me? 我认为以缓冲方式读取图像文件的方式似乎有问题,您能帮我吗?

Thanks in advance! 提前致谢!

The use of ByteArrayOutputStream is redundant, and you are sending its entire contents every time it grows. ByteArrayOutputStream的使用是多余的,并且每次增长时都将发送其全部内容。 Change your loop as follows: 如下更改循环:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM