✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🧬 Learn how to build RNA-Seq data apps with Python & Dash. Register for the May 20 Webinar!

Display a base64 encoded image on the background of a figure

Hello

I am trying to display a local png picture in the layout of a figure. Looking at this or this topics, I implemented the following code which runs without any error but the output is a blank figure.

Plotly version is 4.3.0

import plotly.graph_objects as go
import base64

image_filename = "../Data/Ovaire5/20160920_153049.png"
encoded_image = base64.b64encode(open(image_filename, 'rb').read())
img = 'data:image/png;base64,{}'.format(encoded_image)

layout = go.Layout(
    images=[go.layout.Image(source=img)],
    template="plotly_white"
)
fig = go.Figure(layout=layout)
fig.show()

I succeed doing this with matplotlib from

img = plt.imread("../Data/Ovaire5/20160920_153049.png")
plt.imshow(img)

But I cannot simply use the output of imread to the plotly images argument.

Thanks for advices

@gvallverdu

One week ago a user confirmed that the code I gave as answer here https://community.plotly.com/t/how-do-i-add-a-background-image-with-animation-graph/35725/2 worked.

1 Like

Thank you.
I missed the decode() step. It works now, with the following code. It seems, that sizex and sizey were mandatory.

image_filename = "../Data/Ovaire5/20160920_153049.png"
encoded_image = base64.b64encode(open(image_filename, 'rb').read())
img = 'data:image/png;base64,{}'.format(encoded_image.decode())

layout = go.Layout(
    images=[go.layout.Image(
        source=img, 
        sizex=1, sizey=1, 
        yanchor="bottom"
    )],
    template="plotly_white"
)
fig = go.Figure(layout=layout)
fig.show()
2 Likes