Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - convert image to JSON

Tags:

python

json

I need to convert an image (can be any type jpg, png etc.) to JSON serializable.

I looked into the solution here but the accepted solution has a typo and I am not sure how to resolve it.

like image 328
nad Avatar asked Feb 13 '19 00:02

nad


People also ask

Can image be converted to JSON?

An image is of the type "binary" which is none of those. So you can't directly insert an image into JSON. What you can do is convert the image to a textual representation which can then be used as a normal string. The most common way to achieve that is with what's called base64.

Can you convert PNG to JSON?

Yes, you can use PNG to JSON Encoder on any operating system that has a web browser.

How to convert data into JSON file in Python?

you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.


2 Answers

This might get you started:

import json
import base64

data = {}
with open('some.gif', mode='rb') as file:
    img = file.read()
data['img'] = base64.encodebytes(img).decode('utf-8')

print(json.dumps(data))
like image 95
Cole Tierney Avatar answered Oct 17 '22 14:10

Cole Tierney


Python 2

As the base64.encodebytes() has been deprecated in base64, the code snippet above can be modified as follows:

import json
import base64

data = {}
with open('some.gif', mode='rb') as file:
    img = file.read()

data['img'] = base64.b64encode(img)
print(json.dumps(data))

Then, use base64.b64decode(data['img']) to convert back.

like image 23
Erfan Avatar answered Oct 17 '22 16:10

Erfan