2

I am trying to send an image from Socket server (Java) to socket client (Python) but the received image in client has an incorrect size and does not open. I don't know what am I doing wrong. Any suggestions?

Server (Java):

...
BufferedImage image = ImageIO.read (new File("c:\\tmp\\File.png"));
ImageIO.write(image, "png", connectionSocket.getOutputStream());
...

Client (Python):

try:
   client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect( host , port )
    data = client_socket.recv( 1024 )
    fp = open ( path, "wb" )
    while data:
        data = client_socket.recv( 1024 )
        if data:
            if not data: break
            fp.write  ( data )
            fp.flush()
        fp.close()
        client_socket.close()
except:
    print "could not connect to %s:%s " %( host, port 
3
  • use base64 encoding to transfert Commented Mar 31, 2016 at 14:15
  • Thank you Could you please explain more Commented Mar 31, 2016 at 14:24
  • You must know how many data you will sent to be sure to receive all of them. In java, get your image size (called 's' for example) before transfert, first send the size 's' to the python client, then read 's' next data. Else you can use a end delimiter for your transfert and reading datas while you get it. Commented Mar 31, 2016 at 14:30

1 Answer 1

2

Convert your image to a base64 string (Java), then transfert the string and get back to the image data (python).

In java, to get Image from base64 string:

public static Image image(String base64Img) {
 byte[] b = DatatypeConverter.parseBase64Binary(base64Img);
 ByteArrayInputStream s = new ByteArrayInputStream(b);
 return new Image(s);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.