tkbarb10's picture
download
raw
1.38 kB
"""
Helpers for inlining local image files (PNG, SVG, etc.) as base64 HTML <img> tags.
Use inline_img() anywhere you need an image inside st.markdown(unsafe_allow_html=True).
"""
import base64
from pathlib import Path
_MIME = {
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
}
def inline_img(path: Path | str, height: str = "1.2em", *, fallback: str = "", extra_style: str = "") -> str:
"""
Return an HTML <img> tag with the file base64-encoded into the src.
Args:
path: Absolute or relative path to the image file.
height: CSS height value (e.g. "1.2em", "24px"). Width scales automatically.
fallback: String to return if the file does not exist (e.g. an emoji).
extra_style: Additional CSS to append to the style attribute.
Returns:
HTML string safe to embed inside st.markdown(unsafe_allow_html=True).
"""
p = Path(path)
if not p.exists():
return fallback
mime = _MIME.get(p.suffix.lower(), "image/png")
b64 = base64.b64encode(p.read_bytes()).decode()
style = f"height:{height};vertical-align:middle;display:inline-block;margin:0 3px;"
if extra_style:
style += extra_style
return f"<img src='data:{mime};base64,{b64}' style='{style}'/>"

Xet Storage Details

Size:
1.38 kB
·
Xet hash:
05b9d7ccf9b02251a04be65fe174d5b6d4638d788b9208bae047cdf0d91f888f

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.