通过套接字问题发送图像流 - Android [英] Sending Image Stream over Socket Issue - Android

查看:139
本文介绍了通过套接字问题发送图像流 - Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一个应用程序,它使用SP摄像头拍照并通过套接字发送到服务器。

I've implemented an application that takes a picture with the SP camera and sends it over a socket to the server.

我正在使用以下代码读取本地存储的图像文件并通过套接字以连续的块发送它:

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

我面临的问题是改变了字节数组 data [] 会影响实际发送到服务器的图像数量

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.

下面发布的图片可以帮助您理解:

The images posted below should help you understand:


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

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


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

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


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

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

等等。

您可以想象我能找到一个尺码这允许我发送完整的图像,但这种临时解决方案是不接受的因为任何维度的图像都需要发送。

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?

提前致谢!

推荐答案

使用ByteArrayOutputStream是多余的,并且每次增长时都会发送其全部内容。按如下方式更改循环:

The use of ByteArrayOutputStream is redundant, and you are sending its entire contents every time it grows. 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();

这篇关于通过套接字问题发送图像流 - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆