How to Embed Images into a Dash App

Hi community :wave:

Adding local image files to your Dash Apps can be challenging sometimes as there are multiple ways of doing it.
Thanks to @adamschroeder for highlighting that there were frequent questions been posted related to such challenges.

This post will cover all the best practices to add local images to your Dash App.

First, Place the Image Files inside the Assets Folder

Just create a folder named assets in the root of your app directory. All your static files are recommended to be kept in this folder. Dash will automatically serve all of the files that are included in this folder.

      - app.py
      - assets/
          |-- my-image.png

Once you have your files inside the assets folder, it is easier to access them through various methods:

  • Direct file path

    image_path = 'assets/my-image.png'
    
    html.Img(src=image_path)
    
  • get_asset_url
    Directly access the image in your code by calling app/dash.get_asset_url function and passing your image filename.

    html.Img(src=app.get_asset_url('my-image.png'))   # for Dash version < 2.2.0
    

    Or

    html.Img(src=dash.get_asset_url('my-image.png'))  # for Dash version >= 2.2.0
    
  • Pillow Library
    The Pillow library supports a wide variety of image file formats. The library automatically determines the format based on the contents of the file. To read files from disk, use the open() function in the Image module.

    from PIL import Image
    pil_image = Image.open("assets/my-image.png")
    
    html.Img(src=pil_image)
    
  • Converting a base64 image string
    html.Image supports special base64 encoded strings preceding with the image mime type. This allows you to convert a base64 string format to an image using the base64 module

    import base64
    
    image_path = 'assets/my-image.png'
    
    # Using base64 encoding and decoding
    def b64_image(image_filename):
      with open(image_filename, 'rb') as f:
          image = f.read()
    return 'data:image/png;base64,' + base64.b64encode(image).decode('utf-8')
    
    #calling the above function
    html.Img(src=b64_image(image_path))
    



Demonstrating all the above methods in an example Dash App

from dash import Dash, html
import base64
from PIL import Image

"""
Examples of different methods of adding local images to your Dash App
Note - Recommended to keep image files inside assets folder
- app.py
- assets/
    |-- my-image.png
"""

#Using direct image file path
image_path = 'assets/my-image.png'

#Using Pillow to read the the image
pil_img = Image.open("assets/my-image.png")

# Using base64 encoding and decoding
def b64_image(image_filename):
    with open(image_filename, 'rb') as f:
        image = f.read()
    return 'data:image/png;base64,' + base64.b64encode(image).decode('utf-8')


app = Dash(__name__)

app.layout = html.Div([
    html.H1('Dash Puppies'),

    html.Img(src=image_path),                          # passing the direct file path
    html.Img(src=app.get_asset_url('my-image.png')),    # usign get_asset_url function
   #html.Img(src=dash.get_asset_url('my-image.png'))    Or with newer Dash v2.2.0
    html.Img(src=pil_img),                             # using the pillow image variable
    html.Img(src=b64_image(image_path)),               # using base64 to encode and decode the image file
])

if __name__ == "__main__":
    app.run_server()

12 Likes

@atharvakatre @adamschroeder

Bravo. :clap::clap::clap::clap::clap:. Excellent job :+1: ,
very useful to answer frequently asked questions. Thanks.

2 Likes

I have multiple images and I tried doing it using

image_path = ā€˜assets/my-image.pngā€™

#Using Pillow to read the the image
pil_img = Image.open(ā€œassets/my-image.pngā€)

How can I loop for multiple images ? When I display images in this html.Img(src=pil_img) I do not see any images on my scatter plot.

Hi @pbudavi and welcome to the community!

Not sure what you are trying to do by looping through multiple images. Adding image to a scatter plot is a different scenario, the above solutions are for adding images to your Dash App just like showing images on a webpage.

For images within a plot you can use the fig.add_layout_image function which is documented here - Images in Python

Hey @pbudavi You might find this awesome example from @RenaudLN helpful: Put images inside bubbles - #2 by RenaudLN

It shows how to make a figure like this where each flag is an image:
image

1 Like

This did help thank you.

I was trying to get all images stored in a folder and display the data points as images using jupyter dash. But your solution did help as I was able to accomplish the task. Thanks

1 Like

Hi @atharvakatre

How to link to an image in the assets folder from inside a JavaScript file in the assets folder as well?

For example, if the folder structure is like this:

- app.py
      - assets/
          |-- my-image.png
          |-- my-script.js

How can I link to my-image.png inside my-script.js?

Thank you. How to update the image file in asset folder? I did update the image file but it still show old image. not sure how to do it? Thanks

Have you changed to that new imageā€™s filename in the Dash app? It might still be referring to the old image

Very helpful! Some of these methods work for me, so my issue is solved, but passing the direct file path doesnā€™t seem to work for me when I run this in Jupyter Lab. Think that approach is just a limitation of Jupyter notebooks?

In case anyone has the same issue, running Plotly Dash 2.15.0 on a Windows workspace from a One Drive folder will not work with jpg images. I tried base64 encoding , os.getcwd() coding, using the assets folder, not using the assets folder, and nothing worked. Changed the image to a PNG and didnā€™t need ANY of the Base64 or os functions, it just works straight away as it should. I saw a lot of posts with people claiming the help didnā€™t solve the problem, and they are right. Easiest resolution is convert your JPG to a PNG. Hope this helps someone else not spend way too much time trying to get an HTML image loaded.

For many hours Iā€™ve been struggling with properly encoding a user-uploaded image or PDF to display as the background in a Dash Bootstrap Card. The original post by @atharvakatre is exactly what I needed! Thanks for making this post!!!

2 Likes