matplotlib image to base64 without saving

I am creating a wordcloud image with this code.

       wordcloud = WordCloud(
            background_color='white',
            random_state=30,
            width=1500,
            height=1200,
            font_path = font_path,
            prefer_horizontal=1)
        wordcloud.generate_from_frequencies(frequencies=d)

I show the image with matplotlib like this:

        plt.imshow(wordcloud)
        plt.axis('off')
        plt.show()

I am using this as part of a web app. I want to convert this image to base64 and store as a string as a value in a dictionary key for a specific instance. I see a lot of posts about how to convert images to base64 but it looks like they involve saving the figure locally before encoding. How do I do this without saving anywhere so I can just go from image to string?

This code looks kind of like what I want.

import base64
from PIL import Image
from io import BytesIO

with open("image.jpg", "rb") as image_file:
    data = base64.b64encode(image_file.read())

im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')

If I just did this, would this accomplish my task?

data = base64.b64encode(wordcloud)

1 answer

  • answered 2021-02-22 23:18 Reti43

    If I just did this, would this accomplish my task?

    data = base64.b64encode(wordcloud)

    No. You need to "save" the image, get that bytestream, and encode that to base64. You don't have to save the image to an actual file; you can actually use a buffer.

    w = WordCloud().generate('Test')
    buffer = io.BytesIO()
    w.to_image().save(buffer, 'png')
    b64 = base64.b64encode(buffer.getvalue())
    

    And to convert that back and display the image

    img = Image.open(io.BytesIO(base64.b64decode(b64)))
    plt.imshow(img)
    plt.show()