如何使用 Mqtt 和 python 将图像作为 json 元素发送?
How do I send an image as a json element using Mqtt and python?
我将图像作为 json 元素附加并通过 mqtt 发送。但是我在订户方面没有收到任何东西。如果我删除图像,我会收到 json.
出版商代码:
with open("sample.jpg", "rb") as image_file:
encoded_img_str = base64.b64encode(image_file.read())
response['image'] = encoded_img_str
response['status'] = 'success'
response['filename'] = 'sample.jpg'
json_data = json.dumps(response)
client.publish(TOPIC, json_data);
订阅者代码:
def on_message(client, userdata, msg):
response_message = msg.payload.decode()
response_dict = json.loads(response_message)
print (response_dict['status']) # Prints nothing
img_str = response_dict['image']
decoded_img = base64.b64decode(img_str)
with open("imageToSave.jpg", "wb") as fh:
fh.write(base64.decodebytes(decoded_img))
因为json
格式只支持string
和base64.b64encode
returnbytes
所以json.dumps应该会报错。你可以使用 binacsii
import binascii
with open("sample.jpg", "rb") as image_file::
data = binascii.b2a_base64(image_file.read()).decode()
resp['image'] = data
print(json.dumps(resp))
#converting back to image using binascii.a2b_base64
with open("sample.jpg", "wb") as f2:
f2.write(binascii.a2b_base64(data))
我将图像作为 json 元素附加并通过 mqtt 发送。但是我在订户方面没有收到任何东西。如果我删除图像,我会收到 json.
出版商代码:
with open("sample.jpg", "rb") as image_file:
encoded_img_str = base64.b64encode(image_file.read())
response['image'] = encoded_img_str
response['status'] = 'success'
response['filename'] = 'sample.jpg'
json_data = json.dumps(response)
client.publish(TOPIC, json_data);
订阅者代码:
def on_message(client, userdata, msg):
response_message = msg.payload.decode()
response_dict = json.loads(response_message)
print (response_dict['status']) # Prints nothing
img_str = response_dict['image']
decoded_img = base64.b64decode(img_str)
with open("imageToSave.jpg", "wb") as fh:
fh.write(base64.decodebytes(decoded_img))
因为json
格式只支持string
和base64.b64encode
returnbytes
所以json.dumps应该会报错。你可以使用 binacsii
import binascii
with open("sample.jpg", "rb") as image_file::
data = binascii.b2a_base64(image_file.read()).decode()
resp['image'] = data
print(json.dumps(resp))
#converting back to image using binascii.a2b_base64
with open("sample.jpg", "wb") as f2:
f2.write(binascii.a2b_base64(data))