Skip to content

Instantly share code, notes, and snippets.

@jimkring
Last active May 2, 2024 00:16
Show Gist options
  • Save jimkring/d2c30fda78e031b285070c07797b0148 to your computer and use it in GitHub Desktop.
Save jimkring/d2c30fda78e031b285070c07797b0148 to your computer and use it in GitHub Desktop.
fastui raw html component example
import io
import base64
from typing import Union
from PIL import Image # requires `pillow` package
from fastui.components import Iframe
def iframe_from_html_raw(
raw_html: str,
width: Union[str, int, None] = None,
height: Union[str, int, None] = None,
) -> Iframe:
"""Returns a fastui Iframe component that displays raw HTML content."""
return Iframe(
srcdoc=raw_html,
# todo: ideally `fastui` should make src not required if srcdoc is provided
src="http://required.input.ignored.when.srcdoc.is.valid",
width=width,
height=height,
)
def iframe_from_image_base64(image_base64: str) -> Iframe:
"""Returns a fastui Iframe component that displays a base64 encoded image."""
width, height = get_size_of_base_64_image(image_base64)
# padding is required to make the iframe scrollbars disappear
pad_horizontal = 4
pad_vertical = 10
return iframe_from_html_raw(
html_raw=f'<img src="data:image/png;base64,{image_base64}" width="{width}" height="{height}">',
width=width + 2 * pad_horizontal,
height=height + 2 * pad_vertical,
)
def get_size_of_base_64_image(image_base64: str):
"""Returns the width and height of a base64 encoded image."""
imgdata = base64.b64decode(image_base64)
im = Image.open(io.BytesIO(imgdata))
width, height = im.size
return width, height
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment