Hi everyone
For some reason, I have to use the image in markdown instead of st.image. However, it didnβt work. Do you know how can I do?
a = """Some text
![Cool Image](images/DWAFig22.png)
Some more text"""
st.markdown(a)
Hi everyone
For some reason, I have to use the image in markdown instead of st.image. However, it didnβt work. Do you know how can I do?
a = """Some text
![Cool Image](images/DWAFig22.png)
Some more text"""
st.markdown(a)
Hey @Berk_Demir,
Hard to say with just this snippet, do you have a link to a GitHub repo and can you screenshot the error you get when you try to use st.image()
? (also please add the image code you use)
Happy Streamlit-ing!
Marisa
I am sorry, I think I wasnβt clear. I want to use markdown to show my image. not the st.image. The snippet I have sent you is a markdown text which is later on shwon in Streamlit as st.markdown(a). But, image does not appear.
It is shown as a broken link and the link is: http://localhost:4444/images/DWAFig22.png
Hello again. I have tried with online images and it works. However, images on my computer during localhost application does not work.
https://share.streamlit.io/akrolsmir/streamlit-snippet/main?snippet_id=3biYhJQ4
So you are trying to use markdown to display an image on your app that is stored in your local computer? Why do you want to use markdown instead of the st.image
function?
What does your directory structure look like?
Based on the path you supply you have a /images/
folder in your current working directory and in that folder there should be a DWAFig22.png
can you screenshot the error you get?
if i want to display a markdown file in streamlit, and the markdown file incloud local images , than the images can not display in streamlit web page.
Hi @Berk_Demir, @lt8cn ,
Images in st.markdown
can only be loaded when served by a βserverβ. This is an example of the trick I use when displaying my README.md
files in Streamlit apps, which relies on the code being in GitHub, i.e. the βserverβ. (The example is from https://github.com/asehmi/fastapi-wrapper-apiness.)
Change the list of images and the base URL for your GitHub repo. And it assumes markdown image statements appear in their own line in your .md file.
if st.sidebar.checkbox('Readme', False):
st.markdown('---')
'''
### Readme :smile:
'''
with open('./README.md', 'r', encoding='utf-8') as f:
readme_lines = f.readlines()
readme_buffer = []
images = [
'images/fastapi_wrapper_demo.gif',
'images/full_screenshot.png',
'images/fastapi_wrapper_st_demo.gif',
'images/fastapi_wrapper_installation.gif',
'images/json_data.png',
'images/html_table.png',
'images/pbi_report_m_lang.png',
'images/pbi_report.png',
'images/apiness.png',
'images/fastapi_testimonial.png'
]
for line in readme_lines:
readme_buffer.append(line)
for image in images:
if image in line:
st.markdown(' '.join(readme_buffer[:-1]))
st.image(f'https://raw.githubusercontent.com/asehmi/fastapi-wrapper-apiness/main/{image}')
readme_buffer.clear()
st.markdown(' '.join(readme_buffer))
(This code is from the line beginning here)
HTH,
Arvindra
Bumping this thread because the use case is important. I have tons of markdown files that contain in-line image links to local files. I do not want to have to either a) break them up with st.image links or b) implement something as complicated as the above (although it is as usual cool work by @asehmi). There should be a better way.
Hi @fredzannarbor,
Thanks for bumping this thread up. Iβve created a Streamlit app that shows 2 ways to display images:
st.image
st.markdown
Demo app is available here https://dataprofessor-st-demo-image-markdown-streamlit-app-layled.streamlitapp.com/
Code is available on GitHub here GitHub - dataprofessor/st-demo-image-markdown
Code for implementing these is shown below:
st.image
from PIL import Image
img = Image.open('streamlit-logo-secondary-colormark-darktext.png')
st.image(img)
st.markdown
# img_to_bytes and img_to_html inspired from https://pmbaumgartner.github.io/streamlitopedia/sizing-and-images.html
import base64
from pathlib import Path
from utilities import load_bootstrap
load_bootstrap()
def img_to_bytes(img_path):
img_bytes = Path(img_path).read_bytes()
encoded = base64.b64encode(img_bytes).decode()
return encoded
def img_to_html(img_path):
img_html = "<img src='data:image/png;base64,{}' class='img-fluid'>".format(
img_to_bytes(img_path)
)
return img_html
st.markdown(img_to_html('streamlit-logo-secondary-colormark-darktext.png'), unsafe_allow_html=True)
Thanks! This is pretty helpful, but doesnβt quite solve my use case. I have many long markdown files like this:
asdsafd
asdfasdfas
asdfsaf
image with local links
sfasdfadf
asdfasdf
sdfsafd
image with local links
asfasfdaf
asdfasf
It is not practical for me to break all these files into chunks and insert st.markdown(img_to_html) commands in between the chunks. I could write something to look for local links and chunk before and after, but that sounds potentially error-prone.
Maybe this is utopian, but I think Streamlit ought to be able to read a markdown file with standard markdown components like images and do its best to render the whole thing. If it comes across a link to a local image, it should see if it can reach the image and display it; if it canβt, it can emit some sort of warning or place a small βno luckβ image.
Aha, I see what you mean. You want to be able to read in several images from markdown files.
What we want to achieve here is a unique use case that may require some creative solutions.
Iβve implemented something similar in the 30 Days of Streamlit app.
Instead of storing text and image URL inside a single long markdown file, Iβve split it into: markdown and CSV file.
The markdown file contains only the text while the CSV file contains the image file name and figure caption text.
Practically, the user selects from a select box one of 30 possible options (Days 1-30) and a for loop is implemented to display one of 30 possible markdown/CSV files. f-strings is then used to append the selected day into the relative URL so that the appropriate markdown and images are displayed.
Markdown files are found inside the content/
directory while CSV files are located in content/figures
.
The actual images are located at content/images
π¦
ββ .streamlit
β ββ config.toml
ββ 3AF34648-C61D-47CE-9E56-C496C5A7C240.jpeg
ββ LICENSE
ββ README.md
ββ content
β ββ Day1.md
β ββ Day10.md
β ββ Day11.md
β ββ Day12.md
β ββ Day13.md
β ββ Day14.md
β ββ Day15.md
β ββ Day16.md
β ββ Day17.md
β ββ Day18.md
β ββ Day19.md
β ββ Day2.md
β ββ Day20.md
β ββ Day21.md
β ββ Day22.md
β ββ Day23.md
β ββ Day24.md
β ββ Day25.md
β ββ Day26.md
β ββ Day27.md
β ββ Day28.md
β ββ Day29.md
β ββ Day3.md
β ββ Day30.md
β ββ Day4.md
β ββ Day5.md
β ββ Day6.md
β ββ Day7.md
β ββ Day8.md
β ββ Day9.md
β ββ figures
β β ββ Day1.csv
β β ββ Day20.csv
β β ββ Day6.csv
β ββ images
β ββ 0CEEBB8C-29FB-4B85-9932-CEF642777A8A.jpeg
β ββ 2C9104F7-CF84-4DAF-9004-52BB4644CF28.png
β ββ 77EC58A5-25FD-4477-A74E-421333312514.jpeg
β ββ 7A7B0072-71ED-42BD-B985-B0D35CF03A1F.jpeg
β ββ 8032B4CC-A9BD-4B4F-8DFB-EBE7326886DE.jpeg
β ββ 8085E82C-304F-48EE-8AD6-3F941E31860B.jpeg
β ββ 8ED4483A-58C6-4F76-BE59-C8CC6DCDB95E.jpeg
β ββ F8DCC7EB-D497-426D-904F-6941E2C4B750.jpeg
β ββ readme.md
ββ requirements.txt
ββ streamlit-logo-secondary-colormark-darktext.png
ββ streamlit_app.py
Β©generated by Project Tree Generator
Of particular note is that not all 30 Days will contain images because there are only 3 Days (Days 1, 6 and 20) that contain images and thus there are 3 CSV files (containing the image file name and figure caption as mentioned above).
For example, Day 1 contains both text and images (from markdown and CSV files, respectively). Images are appended after markdown text as shown below:
img,figure,caption
2C9104F7-CF84-4DAF-9004-52BB4644CF28.png, Figure 1, Streamlit demo app is launched via "streamlit hello"
An excerpt of the code in streamlit_app.py
file is shown below:
# Display content
for i in days_list:
if selected_day == i:
st.markdown(f'# ποΈ {i}')
j = i.replace(' ', '')
with open(f'content/{j}.md', 'r') as f:
st.markdown(f.read())
if os.path.isfile(f'content/figures/{j}.csv') == True:
st.markdown('---')
st.markdown('### Figures')
df = pd.read_csv(f'content/figures/{j}.csv', engine='python')
for i in range(len(df)):
st.image(f'content/images/{df.img[i]}')
st.info(f'{df.figure[i]}: {df.caption[i]}')
The GitHub repo for 30 Days app is available here: GitHub - streamlit/30days: #30DaysOfStreamlit is a 30-day social challenge for you to build and deploy Streamlit apps.
Hope this helps
bumping this because its a bug, I believe github pages uses jeckyl to do the rendering if that helps. Streamlit has quickly become a platform of choice for when I want to do quick prototyping and this would help me quickly build cool stuff
Great example!
I modified a bit your functions and implemented a replacement of markdown images:
import os
import re
import base64
from pathlib import Path
import streamlit as st
def markdown_images(markdown):
# example image markdown:
# ![Test image](images/test.png "Alternate text")
images = re.findall(r'(!\[(?P<image_title>[^\]]+)\]\((?P<image_path>[^\)"\s]+)\s*([^\)]*)\))', markdown)
return images
def img_to_bytes(img_path):
img_bytes = Path(img_path).read_bytes()
encoded = base64.b64encode(img_bytes).decode()
return encoded
def img_to_html(img_path, img_alt):
img_format = img_path.split(".")[-1]
img_html = f'<img src="data:image/{img_format.lower()};base64,{img_to_bytes(img_path)}" alt="{img_alt}" style="max-width: 100%;">'
return img_html
def markdown_insert_images(markdown):
images = markdown_images(markdown)
for image in images:
image_markdown = image[0]
image_alt = image[1]
image_path = image[2]
if os.path.exists(image_path):
markdown = markdown.replace(image_markdown, img_to_html(image_path, image_alt))
return markdown
with open("README.md", "r") as readme_file:
readme = readme_file.read()
readme = markdown_insert_images(readme)
with st.container():
st.markdown(readme, unsafe_allow_html=True)
Thanks a lot,itβs working,Awesome job
This doesnβt work with private repos. Is there any other way?
I think there are loads of different usecases why to use the st.markdown.
But for me, all I wanted was to round the edges of my imagesβ¦
I managed with this:
import streamlit as st
from PIL import Image, ImageDraw
def round_corners(image, radius):
width, height = image.size
mask = Image.new("L", (width, height), 0)
draw = ImageDraw.Draw(mask)
draw.rounded_rectangle((0, 0, width, height), radius, fill=255)
result = Image.new("RGBA", (width, height))
result.paste(image, (0, 0), mask)
return result
# Load your image
image = Image.open("images/your_image.jpg")
# Set the corner radius for rounding
corner_radius = 20 # Adjust the radius as needed
# Round the corners of the image
rounded_image = round_corners(image, corner_radius)
# Display the rounded image using Streamlit
st.image(rounded_image, caption="Rounded Image", use_column_width=None)
P.S This unfortunately does not work with .gif files. Does anyone have a better solution?
Cheers
Fred
I guess you can use markdown and CSS for that.
I have problem displaying in st.markdown as well (display local image file). and Itβs fix with using this comment. Confirm & Thank you.
Glad to hear that it is helpful and working.
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.