简体   繁体   中英

sending Image from Socket server (java) to socket client (python)

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 

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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