How to receive an image with UDP?

edited May 2015 in How To...

Hi! I'm using UDP to send an image from a program to another.

this function sends the image with UDP to the other program when the facedetect detects a face in a video/camera

void sendImg(PImage img){
  BufferedImage bimg = new BufferedImage( img.width,img.height, BufferedImage.TYPE_INT_RGB );
  img.loadPixels();
  bimg.setRGB( 0, 0, img.width, img.height, img.pixels, 0, img.width);
  ByteArrayOutputStream baStream  = new ByteArrayOutputStream();
  BufferedOutputStream bos    = new BufferedOutputStream(baStream);

  Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
  ImageWriter writer = (ImageWriter)iter.next();

  ImageWriteParam iwp = writer.getDefaultWriteParam();
  iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

  ImageOutputStream stream = null;

  try {
    stream = ImageIO.createImageOutputStream(bos) ;
  } 
  catch (IOException e) {
    e.printStackTrace();
  }

  writer.setOutput(stream);

  IIOImage imgb = new IIOImage(bimg, null, null);

  try {
    writer.write(null, imgb, iwp);
  } 
  catch (IOException e) {
    e.printStackTrace();
  }

  writer.dispose();
  byte[] packet = baStream.toByteArray();
  println("Sending datagram with " + packet.length + " bytes");
  try {
    ds.send(new DatagramPacket(packet,packet.length, InetAddress.getByName(ip),clientPort));
  } 
  catch (Exception e) {
    e.printStackTrace();
  } 
}

but in the other program I don't know how to do to receive this array of bites and save it as an image jpg in a data carpet. Someone knows how to do it or has any suggestion?

Tagged:
Sign In or Register to comment.