Skip to content

Instantly share code, notes, and snippets.

@jaidevd
Created December 2, 2025 07:04
Show Gist options
  • Select an option

  • Save jaidevd/eafcc296e5f160c4b90070085e3b8bb2 to your computer and use it in GitHub Desktop.

Select an option

Save jaidevd/eafcc296e5f160c4b90070085e3b8bb2 to your computer and use it in GitHub Desktop.
Embedding images in HTML via data-urls
#!/usr/bin/env python3
"""
Generate an HTML page that embeds an image as a data URL.
Usage:
python embed_image.py path/to/image.png output.html
"""
import argparse
import base64
import mimetypes
from pathlib import Path
def encode_image_to_data_url(image_path: Path) -> str:
"""Return a data URL for the given image file."""
mime_type, _ = mimetypes.guess_type(image_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError(f"Could not determine image MIME type for {image_path}")
data = image_path.read_bytes()
encoded = base64.b64encode(data).decode("ascii")
return f"data:{mime_type};base64,{encoded}"
def build_html(data_url: str, image_name: str) -> str:
"""Create a minimal HTML document that displays the embedded image."""
return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Embedded Image</title>
</head>
<body>
<h1>Embedded image: {image_name}</h1>
<img src="{data_url}" alt="{image_name}" />
</body>
</html>
"""
def main() -> None:
parser = argparse.ArgumentParser(
description="Create an HTML page embedding an image as a data URL."
)
parser.add_argument("image", type=Path, help="Path to the image file")
parser.add_argument(
"output",
type=Path,
nargs="?",
default=Path("embedded_image.html"),
help="Path to write the HTML file (default: embedded_image.html)",
)
args = parser.parse_args()
data_url = encode_image_to_data_url(args.image)
html = build_html(data_url, args.image.name)
args.output.write_text(html, encoding="utf-8")
print(f"Wrote HTML with embedded image to {args.output}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment