ZeroMQ pyzmq send jpeg image over tcp
Asked Answered
B

3

6

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?

Berliner answered 16/7, 2014 at 22:6 Comment(0)
S
8

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()
Schinica answered 17/7, 2014 at 13:10 Comment(2)
you can convert bytearray to bytes directly. base64 is a little slower.Oakum
wow you can just send big file in 1 message? can you explain what op did wrong that you fixed?Gulosity
S
2

You can try imagezmq. It's specially built for transporting images using PyZMQ messaging.

Sender

import socket
import imagezmq

sender = imagezmq.ImageSender(connect_to='tcp://receiver_name:5555')

sender_name = socket.gethostname() # send your hostname with each image

image = open("test1.jpg",'rb')
sender.send_image(sender_name, image)

Receiver

import imagezmq

image_hub = imagezmq.ImageHub()

sender_name, image = image_hub.recv_image()
image_hub.send_reply(b'OK')
Selective answered 4/2, 2020 at 8:16 Comment(0)
I
0

Zero-copy string manipulations on C-strings

( from enter link description here )

Bytes and Strings Note If you are using Python >= 2.6, to prepare your PyZMQ code for Python3 you should use the b'message' syntax to ensure all your string literal messages will still be bytes after you make the upgrade.

The most cumbersome part of PyZMQ compatibility from a user’s perspective is the fact that, since ØMQ uses C-strings, and would like to do so without copying, we must use the Py3k bytes object

Inveigle answered 18/7, 2014 at 3:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.