Site icon High Voltages

Send and Receive Image using MQTT protocol in Python

send images using mqtt protocol python

send images using mqtt protocol python

In this article, you will learn how you can send images or any text file using MQTT protocol in Python.

To start this tutorial, i will recommend some pre-requisites, which i have covered in my previous tutorials. You should know what is mqtt protocol, how publish/subscribe model works, how to select topic names and how to use MQTT protocol in python.

The applications of MQTT protcol is not only limited to the sending messages, but it is also capable of sending Images and audios.

Publish Image using MQTT protcol

The publishing of Image using MQTT protcol is quite straight forward method. Following image explains the methodology we are going to use in this tutorial.

how to send image using MQTT protocol
how to send image using MQTT protocol

The first thing we need to do is read our image file or any other kind of file in python.

with open("./test.jpg",'rb') as file:
    filecontent = file.read()

After reading the file, we convert the image to byte array.

    byteArr = bytearray(filecontent)

and then we publish the byte array to the topic to which we want to send our Image. In this case, we are sending Image to topic photos using the following line.

    result = client.publish(topic,byteArr,2)
msg_status = result[0]
if msg_status == 0:
    print(f"message : Message sent to topic {topic}")
else:
    print(f"Failed to send message to topic {topic}")

The byte array will be published to the topic. Following is the complete code that will help you publish any image using mqtt protocol in python programming language.

Python MQTT publish message and Images Explained

import time
from paho.mqtt import client as mqtt_client

broker = 'broker.hivemq.com'
port = 1883
topic = "photos"
client_id = 'your client id'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Successfully connected to MQTT broker")
        else:
            print("Failed to connect, return code %d", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def publish(client):
    with open("./test.jpg",'rb') as file:

        filecontent = file.read()
        byteArr = bytearray(filecontent)
        print(byteArr)
        result = client.publish(topic,byteArr,2)
    msg_status = result[0]
    if msg_status == 0:
        print(f"message sent to topic {topic}")
    else:
        print(f"Failed to send message to topic {topic}")

def main():
    client = connect_mqtt()
    client.loop_start()
    publish(client)
    time.sleep(5)
    client.loop_stop()


if __name__ == '__main__':
    main()

The above code uses the paho-mqtt library, so make sure you have installed that library by typing the following command in the terminal.

pip3 install paho-mqtt

For this tutorial, I am using the free hivemq public MQTT broker. The credentials you see in the code broker address, port are hivemq public mqtt broker credentials. Topic “photos” is the topic on which we will be publishing our image or text file and the client id must be unique. Firstly we connects to the mqtt broker using the connect_mqtt function defined in the code, the function is self descriptive but in short it uses the above mentioned credentials and connect to the above mentioned broker.

Then, we need to start the loop, there are multiple ways to use mqtt client loop in python for example you could have used loop_forever but in this case we are starting and stopping loop manually, where as the loop_forever function is blocking. Then we are are calling the function publish which converts our image to byte array and publish it to the topic “photos”. Ta da thats it !!!

You can use another conversion

Instead of encoding our image to byte array, you can also encoding the image to base64. To convert the Image to base64, you can use the following publish function.

import base64

def publish(client):
    with open("./test.jpg",'rb') as file:
        filecontent = file.read()
        base64_bytes = base64.b64encode(filecontent)
        base64_message = base64_bytes.decode('ascii')
        result = client.publish(topic,base64_message,0)
    msg_status = result[0]
    if msg_status == 0:
        print(f"message sent to topic {topic}")
    else:
        print(f"Failed to send message to topic {topic}")

Receive Image using MQTT protcol

For receiving the image, the concept is same but reversed. We need to subscribe to the topic “photos” in order to receive the byte array or base64 message. When Image or any file is published on the topic, we will receive the message. The first thing we need to do is create an jpg file.

f = open('receive.jpg', 'wb')

Then we will write the received byte array or base64 message to the file.

f.write(msg.payload)
f.close()

In case, you used base64 then you can use the following code to convert it back to the image. But firstly, make sure you have imported the base64 library.

f = open('receive.jpg', 'wb')
msg = str(message.payload.decode('utf-8'))
img = msg.encode('ascii')
final_img = base64.b64decode(img)
f.write(final_img)
f.close()

Python MQTT Subscription and receiving Images Explained

from paho.mqtt import client as mqtt_client

broker = 'broker.hivemq.com'
port = 1883
topic = "photos"
topic_sub = "photos"
client_id = 'xzcfghjt123'

def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Successfully connected to MQTT broker")
        else:
            print("Failed to connect, return code %d", rc)
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        f = open('receive.jpg', 'wb')
        f.write(msg.payload)
        f.close()
        print ('image received')

    client.subscribe(topic_sub)
    client.on_message = on_message

def main():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()
    
if __name__ == '__main__':
    main()

The code is very similar to the publish code,but instead of publish function we now have subscribe function. Firstly, we are connecting to the MQTT broker and after connecting we are subscribing to the topic “photos”, In the subscribe function we also defined the client.on_Message function, which means whenever we will receive a message, this function will be called. In this code, we are using loop_forever function since we want to keep listening for data.

Conclusion

I hope this tutorial helps you understand, how you can send images using MQTT protocol. If you do so, also check how to create MQTT dashboard using python, that can help you create a nice GUI and with a bit of extra effort, you can upload and receive images using the GUI. Or if you want to create a web based dashboard or android dashboard, don’t worry I have got you covered, this tutorial will help you create a web dashboard for MQTT.

Exit mobile version