java 如何使用UDP套接字传输jpg图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26571640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:10:09  来源:igfitidea点击:

How to transfer jpg image using UDP socket

javasocketsudp

提问by Asanga Ranasinghe

I want to transfer an jpg image via an UDP connection. I want a java code to convert the image into a byte array and to recreate the jpg file on the other side.

我想通过 UDP 连接传输 jpg 图像。我想要一个 java 代码将图像转换为字节数组并在另一侧重新创建 jpg 文件。

Code I tried

我试过的代码

Image To ByteArray

图像转字节数组

    BufferedImage img = ImageIO.read(new File("src/test.jpg"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();        
    ImageIO.write(img, "jpg", baos);
    baos.flush();
    byte[] buffer = baos.toByteArray();
    byte[] buff = new byte[1024];
    int c=0;

    DatagramSocket clientSocket = new DatagramSocket();       
    InetAddress IPAddress = InetAddress.getByName("192.168.43.1");
    System.out.println(buffer.length);
    for(int i=0;i<buffer.length;i++){
        buff[c] = buffer[i];
        c++;
        if(i%1023==0){
            DatagramPacket packet = new DatagramPacket(buff, buff.length, IPAddress, 9876);
            buff = new byte[1024];
            c=0;
            clientSocket.send(packet);

            System.out.println("sent a mini-packet");
        }
    }

ByteArray To image

ByteArray 到图像

tv = (TextView)findViewById(R.id.recv_message);
try {
  DatagramSocket clientsocket=new DatagramSocket(9876);
  byte[] receivedata = new byte[1024];
  while(true)
  {
    DatagramPacket recv_packet = new DatagramPacket(receivedata, receivedata.length);
    Log.d("UDP", "S: Receiving...");

    clientsocket.receive(recv_packet);       

    byte[] buff = recv_packet.getData();
    final Bitmap new_img = BitmapFactory.decodeByteArray(buff, 0,
            buff.length);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            tv.setText("received");
            ImageView image = (ImageView) findViewById(R.id.test_image);
            image.setImageBitmap(new_img);
        }
    });



    InetAddress ipaddress = recv_packet.getAddress();
    int port = recv_packet.getPort();
    Log.d("IPAddress : ",ipaddress.toString());
    Log.d(" Port : ",Integer.toString(port));
  }
} catch (Exception e) {
  Log.e("UDP", "S: Error", e);
  runOnUiThread(new Runnable() {
      @Override
      public void run() {
          tv.setText("Error Occured");
      }
  });
}

回答by Kunjan Thadani

There is a slight problem in the way the image is sent. Initially the image is converted into byte[] and then the individual bytes are sent i.e, the complete image is broken and sent through different smaller packets.

图片的发送方式有点问题。最初,图像被转换为​​ byte[],然后发送单个字节,即完整的图像被破坏并通过不同的小数据包发送。

Now, when you try to receive the packets each of these packet is received individually and an image is being created everytime a small packet is received.

现在,当您尝试接收数据包时,每个数据包都会被单独接收,并且每次收到一个小数据包时都会创建一个图像。

For ex. let image be of 1024 bytes. You are sending its individual bytes like 1, then 2, ..... 1024. While receiving them, say packet 1 is received, it is creating an image with that single packet. Similarly, when 2nd packet arrives, another image is being created.

例如。让图像为 1024 字节。您正在发送它的单个字节,例如 1,然后是 2,..... 1024。在接收它们时,假设收到了数据包 1,它正在使用该单个数据包创建一个图像。同样,当第二个数据包到达时,正在创建另一个图像。

But an image is to be created with complete 1024 bytes. That is why, you are not getting the result you want.

但是要创建一个完整的 1024 字节的图像。这就是为什么你没有得到你想要的结果。

You need to implement a mechanism to buffer them into a single byte[] & then form an image.

您需要实现一种机制将它们缓冲到单个字节 [] 中,然后形成一个图像。

For now, just do one thing. Send the image in a single unit i.e, create a byte[] from the image & send it directly without breaking it or sending the bytes individually from loop.

现在,只做一件事。在单个单元中发送图像,即,从图像创建一个字节 [] 并直接发送它而不会破坏它或从循环中单独发送字节。

 BufferedImage img = ImageIO.read(new File("src/test.jpg"));
 ByteArrayOutputStream baos = new ByteArrayOutputStream();        
 ImageIO.write(img, "jpg", baos);
 baos.flush();
 byte[] buffer = baos.toByteArray();

 DatagramSocket clientSocket = new DatagramSocket();       
 InetAddress IPAddress = InetAddress.getByName("192.168.43.1");
 System.out.println(buffer.length);

  DatagramPacket packet = new DatagramPacket(buffer, buffer.length, IPAddress, 9876);

  clientSocket.send(packet);

Now, when you receive the packet, a complete image can be formed as all 1024 bytes will be received at once.

现在,当您收到数据包时,可以形成一个完整的图像,因为将一次接收所有 1024 个字节。