Cannot convert to a numpy array a base64 encoded image returned by fig.to_image()

In order to use MoviePy to create a videoclip from Plotly figs I need to convert a base64 encoded image returned by fig.to_image() to a numpy array, but I’m getting the following error:
cannot identify image file <_io.BytesIO object at 0x00000165FB0ABAF0

import plotly.graph_objects as go
import numpy as np
np.random.seed(1)

N = 100
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
sz = np.random.rand(N) * 30

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=x,
    y=y,
    mode="markers",
    marker=go.scatter.Marker(
        size=sz,
        color=colors,
        opacity=0.6,
        colorscale="Viridis"
    )
))
fig.update_layout(width=600, height=450)

################
import base64
import io 
from PIL import Image

fig_bytes = fig.to_image(format="png", width=600, height=450)
#print(fig_bytes[:20])

decoded = base64.b64decode(fig_bytes)
buf = io.BytesIO(decoded)
img = Image.open(buf)
fig_array = np.asarray(img)

I cannot figure out what is wrong here.

Hi @empet,

The result of fig.to_image is already a bytes object so it doesn’t need to be decoded before creating the BytesIO buffer.

import plotly.graph_objects as go
import numpy as np
np.random.seed(1)

N = 100
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
sz = np.random.rand(N) * 30

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=x,
    y=y,
    mode="markers",
    marker=go.scatter.Marker(
        size=sz,
        color=colors,
        opacity=0.6,
        colorscale="Viridis"
    )
))
fig.update_layout(width=600, height=450)

################
import io 
from PIL import Image

fig_bytes = fig.to_image(format="png", width=600, height=450)

buf = io.BytesIO(fig_bytes)
img = Image.open(buf)
fig_array = np.asarray(img)
fig_array.shape
(450, 600, 4)

Hope that helps! And definitely interested to see what you come up with using MoviePy!
-Jon

1 Like

Hi @jmmease,

Great, thank you!!! :slight_smile: