Utility for constructing an image from a string or bytes The source value will automatically be encoded to base64
(
format: str,
value: str | bytes = "",
attributes: dict[str, Any] | None = None,
)
| 11 | |
| 12 | |
| 13 | def image( |
| 14 | format: str, |
| 15 | value: str | bytes = "", |
| 16 | attributes: dict[str, Any] | None = None, |
| 17 | ) -> VdomDict: |
| 18 | """Utility for constructing an image from a string or bytes |
| 19 | |
| 20 | The source value will automatically be encoded to base64 |
| 21 | """ |
| 22 | if format == "svg": |
| 23 | format = "svg+xml" # noqa: A001 |
| 24 | |
| 25 | if isinstance(value, str): |
| 26 | bytes_value = value.encode() |
| 27 | else: |
| 28 | bytes_value = value |
| 29 | |
| 30 | base64_value = b64encode(bytes_value).decode() |
| 31 | src = f"data:image/{format};base64,{base64_value}" |
| 32 | |
| 33 | return {"tagName": "img", "attributes": {"src": src, **(attributes or {})}} |
| 34 | |
| 35 | |
| 36 | _Value = TypeVar("_Value") |