MQTT 是一种轻量级发布/订阅消息的协议,通常用于具有小型的物联网设备。消息中通常不会包含太多数据,只是传感器值。
但是大多数情况下,MQTT 消息负载是文本,可能是少量文本或 JSON 数据负载。不过,设备如何在 MQTT 消息中发送文件,例如Image图片.jpg格式文件呢?
这期我们通过整理网上的资料,把具体的方式分享给大家!

使用 MQTT 协议发布图像
使用 MQTT 协议发布图像是一种非常直接的方法。下面的图像解释了我们在本期中将要使用的流程。
Step1:首先我们需要在 Python 中读取我们的图像文件或其他类型的文件。
with open("./test.jpg",'rb') as file:
filecontent = file.read()
Step2:读取文件后,我们将图片转换为字节数组。然后我们将字节数组发布到我们想要发送图片的主题。 byteArr = bytearray(filecontent)
Step3:在这种情况下,我们使用以下代码将图片发送到名为 photos 的主题。 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}")
字节数组将发布到主题。以下是一段完整的代码,它将帮助您使用 mqtt 协议在 python 编程语言中发布任何图片: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()
上述代码使用了 paho-mqtt 库,所以在终端中输入以下命令确保已经安装了该库。
对于本期教程,我使用的是免费的 hivemq 公共 MQTT 代理。代码中的 broker 地址、端口凭证是 hivemq 公共 mqtt 代理的凭证。主题“photos”是我们将发布图像或文本文件的主题,客户端 ID 必须是唯一的。
当然也可以使用其他的代理,例如EMQX:
broker = "broker.emqx.io"
port = 1883
timelive=60
image_name="capture.jpg"
Top 5 免费开源MQTT Brokers代理!!!
另一种方式不同将图像编码为字节数组,而是将图像编码为 base64。要将图像转换为 base64,可以使用以下发布函数。
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}")
这两种方式都是可行的。

使用 MQTT 协议接收图像
接收图像的概念是相同的,只是顺序相反。我们需要订阅“photos”主题以接收字节数组或 base64 消息。当图像或任何文件发布到该主题时,我们将接收到消息。首先,我们需要创建一个 jpg 文件。f = open('receive.jpg', 'wb')
然后,我们将接收到的字节数组或 base64 消息写入文件。f.write(msg.payload)
f.close()
如果你使用了 base64,那么可以使用以下代码将其转换回图像。但在执行此操作之前,请确保已经导入了 base64 库。
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()
完整的代码如下所示:
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()
代码与发布代码非常相似,但我们现在使用的是 subscribe 函数而不是 publish 函数。首先,我们连接到 MQTT 代理,连接后我们订阅了“photos”主题。在 subscribe 函数中,我们还定义了 client.on_Message 函数,这意味着每当接收到消息时,该函数将被调用。在这个代码中,我们使用了 loop_forever 函数,因为我们想一直监听数据。
参考链接:
https://boardor.com/blog/detect-objects-and-transmit-images-using-mqtt
https://davidmac.pro/posts/2021-07-21-files-over-mqtt/
https://highvoltages.co/iot-internet-of-things/mqtt/image-using-mqtt-protocol/
阅读原文:原文链接
该文章在 2025/6/23 12:59:24 编辑过