I first convert the image on the server application in bytes:

 public void sendImage(File file) throws IOException {

		ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
		BufferedImage img=ImageIO.read(new File(file.getAbsolutePath()));
		ImageIO.write(img, "jpg", baos);

        os.write(baos.toByteArray());// this is a "new DataOutputStream(clientSocket.getOutputStream());"
          System.out.println("Done! Length is:"+baos.toByteArray().length);


Then my application freezes when trying to convert the bytes array back to image.

public void receiveImage() throws IOException

byte[] bytearray = new byte[4096];
is.readFully(bytearray);// "new DataInputStream(clientSocket.getInputStream());" here my app freezes. and i don't knwo array length. 
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
ImageIO.write(imag, "jpg", new File("abc.jpg"));

this.setLayout(new FlowLayout());
this.add(new ImagePanel(imag));

I probabily done something wrong... Is this a good aproach to transfer images fast?
Can someone help please?

Wow.... I finally made it myself.. after a hard time. So I better post it, for people who seek this too.

//sending image from server
 public void sendImage(File file) throws IOException {
  long len = file.length();
  byte[] byteArray = new byte[(int)len];
  try {
     FileInputStream fstream = new FileInputStream(file);


             os.writeInt((int)len);//send the length
             os.write(byteArray, 0, (int)len);
  } catch(Exception e){}

  System.out.println("Done! "+byteArray.length);

Now the client receives the byte array:

private BufferedImage img;
//cc = the main Frame of the application
//is = new DataInputStream(clientSocket.getInputStream());

                            int len = cc.is.readInt();
                           byte[] byteArray = new byte[len];
//here you have it back
                            img=ImageIO.read(new ByteArrayInputStream(byteArray));;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.