Local image file not shown in components.html

I want to display a local image in streamlit app using components.html. But the image is not getting displayed. The image file is present in the same directory as the code file. Following is the sample code:

components.html(
    """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test Image</title>
    <img src="mathsisfun.png" style="width:50%">
</head>
<body>

</body>
</html> 

    """,
    height=600,
)

I tried this code:


file_ = open("mathsisfun.png", "rb")
contents = file_.read()
data_url = base64.b64encode(contents).decode("utf-8")
file_.close()


components.html(
    """
<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        function loadImg(dataUrl)
        {
            document.getElementById("ItemPreview").src = "data:image/png;base64," + data_url;
        }
    </script>
    <meta charset="UTF-8">
    <title>Test Image</title>
</head>
<body onload="loadImg(dataUrl)">
    <img id="ItemPreview" src="">
</body>
</html> 

    """,
    height=200,
)

But don’t know, how to use the byte date “data_url” in components.html.

Here is the solution.

Following is the code:

components.html(
    f"""
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Test Image</title>
    </head>
    <body>
        <img src="data:image/png;base64,{data_url}">
    </body>
    </html>
    """,
    height=400,
)

Thanks.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.