sa_penguin
sa_penguin

Reputation: 457

How do I send an image as a json element using Mqtt and python?

I am attaching an image as a json element and sending it over mqtt. But I do not receive anything on subscriber side. If I remove the image, I am receiving the json.

Publisher code:

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);

Subscriber code:

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))

Upvotes: 0

Views: 812

Answers (1)

gaurav
gaurav

Reputation: 1339

Because json format only support string and base64.b64encode return bytes so json.dumps should be giving error. you can use 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))

Upvotes: 1

Related Questions