Converting PIL/Pillow image to data URL

Viewed 735

Is it possible to, in Python3, convert a PIL/Pillow Image object into a data:image/png URL such that, when pasted into a browser address bar, the image appears?

My attempts so far have failed:

"data:image/png,{}".format(image_obj.tobytes())

Alternatively, is there any other good way to send images to a remote user from a Python script? Image hosting sites would be good but often are expensive / have no Python API / require signing up and logging in. At the moment I intend to use a service like Pastebin to store the image in its text form and simply send the URL to the user.

1 Answers

Actually you are using the wrong prefix. You should do:

img_data_url = 'data:image/jpeg;base64,' + base64_image_string

Some useful stuff:

import base64
import io
from PIL import Image


def pillow_image_to_base64_string(img):
    buffered = io.BytesIO()
    img.save(buffered, format="JPEG")
    return base64.b64encode(buffered.getvalue()).decode("utf-8")


def base64_string_to_pillow_image(base64_str):
    return Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, "utf-8"))))


# Example for Converting pillow image to base64 data URL to view in browser
my_img = Image.open('my-image.jpeg')
data_url = 'data:image/jpeg;base64,' + pillow_image_to_base64_string(my_img)
# You can put this data URL in the address bar of your browser to view the image
Related