In plotly dash, how do I source a local image file to dash.html.Img?

Question:

This is how to source a local image file to the <img> element in html:

<html>
    <h1>This is an image</h1>
    <img src="file:///C:/Users/MyUser/Desktop/Plotly_Dash_logo.png" alt="image"></img>
</html>

This displays the image as expected. But when I try to make the same page using the plotly dash wrapper elements, it does not work:

import dash
from dash import html, dcc

app = dash.Dash(__name__)

app.layout = html.Div([
    html.H1('This is an image'),
    html.Img(src=r'file:///C:/Users/MyUser/Desktop/Plotly_Dash_logo.png', alt='image'),
    ])

if __name__ == '__main__':
    app.run_server(host='0.0.0.0', port=8080, debug=False, use_reloader=False)

The local image file does not display. But if I replace the source with a file from the internet, like 'https://rapids.ai/assets/images/Plotly_Dash_logo.png', it works just fine.

What is going on here?

Asked By: Wilson

||

Answers:

You can try with the solution provided in this old GitHub issue :
https://github.com/plotly/dash/issues/71

It seems it’s not built for local urls 😕

Answered By: SidoShiro92

After some more searching, I found that I could place my image file in a folder named "assets/", then reference it relative to the app folder.

html.Img(src=r'assets/Plotly_Dash_logo.png', alt='image')

I could also use a special method of the app instance dash.Dash.get_asset_url().

html.Img(src=app.get_asset_url('my-image.png'))

Source: https://dash.plotly.com/dash-enterprise/static-assets

Answered By: Wilson

I used another way:

  • open the image file and read the contents
  • encode the data by base64 and decode it
  • add "data:image/jpg;base64, " in front of the string (replace jpg with png for png format images)
  • set string as src
with open(imgfile, "rb") as image_file:
    img_data = base64.b64encode(image_file.read())
    img_data = img_data.decode()
    img_data = "{}{}".format("data:image/jpg;base64, ", img_data)
    # ...
    html.Img(id="tag_id", src=img_data, alt="my image", width="200", height="400", 
    className="img_class")
Answered By: Michael Wittstock
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.