How to load a Base64 encoded Image?

I have a string that is a Base64 encoded image. How do I load it as a fastai Image object?

Hi Vishal

If you already have the string encoded as a Base64 image, then

import io
import base64
from fastai.vision import *

image_bytes = io.BytesIO(base64.b64decode(image_encoded_as_string))
image = open_image(image_bytes)  #this method comes from fastai.vision

If you want read your image in grayscale, don’t forget pass the keyword convert_mode='L' to open_image

good luck

Thank you

@edxz7, I know this is an old post, but is that method for Base64 images like this data:image/jpeg;base64,/9j/4AAQSkZJRgABAQA... or images without the data:image/jpeg;base64 part? If so, how do I remove it? Currently, I am using a PIL image like this:

   b = b'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...'
   z = b[b.find(b'/9'):]
   im = Image.open(io.BytesIO(base64.b64decode(z))).save('result.jpg')

Can I use that somehow? Sorry to bother you! Thanks in advance for any help!

Base64 encoding enables us to convert bytes containing binary or text data to ASCII characters. By encoding the data, we improve the chances of it being processed correctly by various systems. Some systems don’t understand the data in bytes format, so we have to convert the data.

To convert image to base64 string, use base64.b64encode() method in Python.

As per one of the above community user,

If you already have the string encoded as a Base64 image, then

import io
import base64
from fastai.vision import *

image_bytes = io.BytesIO(base64.b64decode(image_encoded_as_string))
image = open_image(image_bytes)  #this method comes from fastai.vision

If you want to read your image in grayscale, don’t forget to pass the keyword convert_mode='L' to open_image

1 Like