nad
nad

Reputation: 2860

Python - convert image to 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.

Upvotes: 15

Views: 34396

Answers (3)

Luca Di Liello
Luca Di Liello

Reputation: 1643

You should first convert the image into a string. Suppose you loaded the image with Image.open('/path/to/image'), then you could do:

import io
import base64
from PIL import Image

def image2string(image: Image.Image, _format: str = 'PNG') -> str:
    r""" Convert Pillow image to string. """
    if _format == 'JPEG':
        image = image.convert('RGB')
    img_bytes_arr = io.BytesIO()
    image.save(img_bytes_arr, format=_format)
    img_bytes_arr.seek(0)
    img_bytes_arr = img_bytes_arr.read()
    img_bytes_arr_encoded = base64.b64encode(img_bytes_arr)
    res = img_bytes_arr_encoded.decode('utf-8')
    return res


def string2image(string: str) -> Image.Image:
    r""" Convert string to Pillow image. """
    img_bytes_arr = string.encode('utf-8')
    img_bytes_arr_encoded = base64.b64decode(img_bytes_arr)
    image = Image.open(io.BytesIO(img_bytes_arr_encoded))
    return image

Then, use image2string to transform you image into a string that you could put into JSON files. string2image allows you to convert the string back into a Pillow image.

Upvotes: 1

Cole Tierney
Cole Tierney

Reputation: 10324

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

Upvotes: 26

Erfan
Erfan

Reputation: 372

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.

Upvotes: 7

Related Questions