✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Local image for layout.images

Hi !

I am facing a problem, to add a background image to my plot. My app is serverless, and the image is provided by the user, through an input type=‘file’.

However, I cannot load the image neither using a relative path or absolute path. Here is the code :

const input_file = document.getElementById("img_file").files[0];

let update = {
            images: [
            {
                source: `./img/${input_file.name}`,
                xref: "paper",
                yref: "paper",
                sizing: "stretch",
                x: 0,
                y: 0,
                sizex: 1,
                sizey: 1,
                opacity: 0.4,
                xanchor: "left",
                yanchor: "bottom"
            }]
}
Plotly.relayout(GRAPHDIV, update);

Is there a solution for that ?

Regards,
Marion

Hi @marion,

The source for a local image passed to layout should be a base64 encoded image. Here is a python example:
https://community.plotly.com/t/how-do-i-add-a-background-image-with-animation-graph/35725/2.

1 Like

Thank you a lot, it works perfectly !

Here is my solution for encoding in base64, if someone ever needs it :

        var FR = new FileReader();
        FR.addEventListener("load", function(e) {
            document.getElementById('img_file').src = e.target.result;

            let update = {
                images: [
                {
                    source: `${document.getElementById('img_file').src}`,
                    xref: "paper",
                    yref: "paper",
                    sizing: "stretch",
                    x: 0,
                    y: 0,
                    sizex: 1,
                    sizey: 1,
                    opacity: 0.4,
                    xanchor: "left",
                    yanchor: "bottom"
                }]
            }
            Plotly.relayout(GRAPHDIV, update);
        });
        FR.readAsDataURL(document.getElementById("img_file").files[0]);

Regards,
Marion