Reputation: 3
I am trying to send an image using MQTT. I have been able to send and receive other kinds of data using mqtt but for the image I am not receving anything.
I am using base64 to convert image into bytes and then publish it to a broker. Then on the subcriber side I am using base64 to convert it into image again and save the image in the working directory.
This is my publisher
import paho.mqtt.client as mqtt
import time
import base64
mqttBroker ="test.mosquitto.org"
client = mqtt.Client("Temperature_Inside")
client.connect(mqttBroker)
while True:
with open("car.jpg","rb") as image:
img = image.read()
message =img
base64_bytes = base64.b64encode(message)
base64_message =base64_bytes.decode('ascii')
client.publish("TEMPERATURE", base64_message)
print("Just published to topic TEMPERATURE")
time.sleep(1)
This is my subscriber
import paho.mqtt.client as mqtt
import time
import base64
mqttBroker ="test.mosquitto.org"
client = mqtt.Client("Smartphone")
client.connect(mqttBroker)
client.loop_start()
client.subscribe("TEMPERATURE")
def on_message(client, userdata, message):
msg = str(message.payload.decode("utf-8"))
img = msg.encode('ascii')
final_msg = base64.b64decode(img)
open('received_image.jpg','wb').write(final_msg)
client.on_message=on_message
time.sleep(30)
Upvotes: 0
Views: 2215
Reputation: 207798
There's no need to base64 encode/decode images with MQTT as it is perfectly able to transmit binary data such as images.
So, you can publish like this:
with open("car.jpg","rb") as image:
img = image.read()
client.publish("images", image)
and subscribe like this:
def on_message(client, userdata, message):
open('received_image.jpg','wb').write(message.payload)
Upvotes: 0