🛠️ToolsShed

Data URL Encoder

Convert files to base64 Data URLs for embedding in HTML and CSS.

Drop a file here or click to upload

Preguntas Frecuentes

Implementación de Código

import base64
import mimetypes
from pathlib import Path

def file_to_data_url(filepath: str) -> str:
    """Convert a file to a base64 Data URL."""
    path = Path(filepath)
    mime_type, _ = mimetypes.guess_type(filepath)
    if mime_type is None:
        mime_type = "application/octet-stream"

    with open(path, "rb") as f:
        data = f.read()

    encoded = base64.b64encode(data).decode("utf-8")
    return f"data:{mime_type};base64,{encoded}"

# Example usage
url = file_to_data_url("image.png")
print(url[:80] + "...")
print(f"Total length: {len(url)} chars")

# Embed in HTML
html = f'<img src="{url}" alt="Embedded image">'

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.