I need to save a png image to a json file in python. In addition, the beginning of the json file must look like this:
{"image":"data:image/jpeg;base64,/etc.
I suspect that this means that I also need to convert it into jpeg format.
This is what I've tried this far:
import base64, json
filename = 'example_png.png'
f = open(filename, 'rb')
img_data = f.read()
f.close()
enc_data = base64.b64encode(img_data)
json.dump({'image':enc_data}, open('example_png.json', 'w'))
This resulted in the the following error: TypeError: Object of type bytes is not JSON serializable
I've also played around with decoding. For example, I added
enc_data = enc_data.decode('utf-8')
before saving to the json file. Then something was saved to the file, but obviously not in the right format.
I would be really grateful for any help.
Try:
import base64
import json
filename = "your_image.png"
with open(filename, "rb") as f_in, open("example_png.json", "w") as f_out:
enc_data = base64.b64encode(f_in.read()).decode("utf-8")
json.dump({"image": f"data:image/png;base64,{enc_data}"}, f_out)
EDIT: To convert the image to Jpeg and save it to Json you can use Pillow
module:
import base64
import json
from io import BytesIO
from PIL import Image
filename = "<your image.jpg|png>"
with open("example_png_jpeg.json", "w") as f_out:
png_image = Image.open(filename)
jpg_buffer = BytesIO()
png_image.save(jpg_buffer, format="JPEG")
enc_data = base64.b64encode(jpg_buffer.getvalue()).decode("utf-8")
json.dump({"image": f"data:image/jpeg;base64,{enc_data}"}, f_out)