Search code examples
imagejpegzeromqpyzmq

ZeroMQ pyzmq send jpeg image over tcp


I am trying to send a jpeg image file through a ZeroMQ connection with pyzmq, but the output is 3 times the size of the input, and no longer a valid jpeg. I load the image and send with...

f = open("test1.jpg",'rb')
strng = f.read()
socket.send(strng)
f.close()

I receive and save with...

message = socket.recv()
f = open("test2.jpg", 'w')
f.write(str(message))
f.close()

I am new to zmq, and I could not find any info on sending images. Has anyone sent images through ZeroMQ, or have any ideas on how to find the problem?


Solution

  • Before sending the file you can "base64" encode it and decode it when received.

    Sending:

    import base64
    f = open("test1.jpg",'rb')
    bytes = bytearray(f.read())
    strng = base64.b64encode(bytes)
    socket.send(strng)
    f.close()
    

    Receiving:

    import base64
    message = socket.recv()
    f = open("test2.jpg", 'wb')
    ba = bytearray(base64.b64decode(message))
    f.write(ba)
    f.close()