简体   繁体   English

读取大小未知的图像字节数组以显示在Imageview中

[英]Read Image Byte Array of Unknown Size to display in Imageview

I was unable to find something similar to my application so I thought I would ask a new question. 我找不到类似于我的应用程序的内容,所以我想问一个新问题。 I am new to developing android (and java in general) but have some prior programming experience in C and Visual Basic. 我是开发android(和Java)的新手,但是有一定的C和Visual Basic编程经验。 I am using a JPEG TTL Camera (Link Sprite LS Y201) and taking a picture to send from a TCP server to an android client device. 我正在使用JPEG TTL相机(Link Sprite LS Y201)并拍照以将其从TCP服务器发送到android客户端设备。 On the client side, I am using an Async task to continuously get the data from the socket. 在客户端,我正在使用Async任务来不断从套接字获取数据。 So far, I have been able to get some bytes and store them in an array. 到目前为止,我已经能够获取一些字节并将其存储在数组中。 Here are my questions: 1. The amount of data coming in from the socket is unknown. 这是我的问题:1.来自套接字的数据量未知。 How to account for that? 如何解释呢? 2. How to check if all the data was read? 2.如何检查是否读取了所有数据? The JPEG image data starts at hex value 0xFFD8 and ending value is 0xFFD9. JPEG图像数据的起始值为十六进制值0xFFD8,结束值为0xFFD9。 3. How to update this data to an imageview? 3.如何将这些数据更新为imageview?

Thank you as well for taking the time to look this over. 也感谢您抽出宝贵的时间对此进行研究。 I really appreciate any help I can get! 我非常感谢我能获得的任何帮助!

The code I currently have is below: 我目前拥有的代码如下:

  // ----------------------- THE NETWORK TASK - begin ----------------------------
public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
    Socket nsocket; //Network Socket
    InputStream nis; //Network Input Stream
    OutputStream nos; //Network Output Stream
    BufferedReader inFromServer;//Buffered reader to store the incoming bytes

    @Override
    protected void onPreExecute() {
        //change the connection status to "connected" when the task is started
        changeConnectionStatus(true);
    }

    @Override
    protected Boolean doInBackground(Void... params) { //This runs on a different thread
        boolean result = false;
        try {
            //create a new socket instance
            SocketAddress sockaddr = new InetSocketAddress("192.168.1.115",5050);
            nsocket = new Socket();
            nsocket.connect(sockaddr, 5000);//connect and set a 10 second connection timeout
            if (nsocket.isConnected()) {//when connected
                nis = nsocket.getInputStream();//get input
                nos = nsocket.getOutputStream();//and output stream from the socket
                BufferedInputStream inFromServer = new BufferedInputStream(nis);//"attach the inputstreamreader"
                while(true){//while connected
                    ByteArrayBuffer baf = new ByteArrayBuffer(256);
                    int msgFromServer = 0;
                    while((msgFromServer = inFromServer.read()) != -1){;//read the lines coming from the socket
                        baf.append((byte) msgFromServer);
                        byte[] ImageArray = baf.toByteArray();
                        publishProgress(ImageArray);//update the publishProgress
                    }

                }
            }
        //catch exceptions
        } catch (IOException e) {
            e.printStackTrace();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = true;
        } finally {
            closeSocket();
        }
        return result;
    }

    //Method closes the socket
    public void closeSocket(){
        try {
            nis.close();
            nos.close();
            nsocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //Method tries to send Strings over the socket connection
    public void SendDataToNetwork(String cmd) { //You run this from the main thread.
        try {
            if (nsocket.isConnected()) {
                nos.write(cmd.getBytes());
                nos.flush();
            } else {
                outputText("SendDataToNetwork: Cannot send message. Socket is closed");
            }
        } catch (Exception e) {
            outputText("SendDataToNetwork: Message send failed. Caught an exception");
        }
    }

    //Methods is called every time a new byte is received from the socket connection
    @Override
    protected void onProgressUpdate(byte[]... values) {
        if (values.length > 0) {//if the received data is at least one byte
            if(values[85]== 255 ){//Start of image is at the 85th byte



                ///This is where I get lost. How to start updating imageview with JPEG bytes?




            }
        }

    }

    //Method is called when task is cancelled
    @Override
    protected void onCancelled() {
        changeConnectionStatus(false);//change the connection to "disconnected"
    }

    //Method is called after taskexecution
    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            outputText("onPostExecute: Completed with an Error.");
        } else {
            outputText("onPostExecute: Completed.");
        }
        changeConnectionStatus(false);//change connectionstaus to disconnected
    }
}
// ----------------------- THE NETWORK TASK - end ----------------------------
  1. On the server side, before sending each image, you could send an integer with the size of the image you're abut to transfer. 在服务器端,在发送每个图像之前,您可以发送一个整数,该整数与要传输的图像大小相同。
  2. The available() function can be used for that. available()函数可用于此目的。 inFromServer.available() == 0 will tell you whether all data was read. inFromServer.available() == 0将告诉您是否已读取所有数据。
  3. The following code will do it: 下面的代码可以做到这一点:

     byte[] ImageArray = baf.toByteArray(); Bitmap bitmap = BitmapFactory.decodeByteArray(ImageArray, 0, ImageArray.length); imageView.setImageBitmap(bitmap); 

Hope you find this useful! 希望你觉得这个有用! Good luck! 祝好运!

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

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