Image to Base64 Converter — Developer Code Samples
Convert images to Base64-encoded data URIs for embedding directly in HTML, CSS, or JSON. This eliminates extra HTTP requests for small images like icons and logos. Python's base64 module and JavaScript's FileReader API handle the conversion natively.
Try the interactive version online:
Open Image to Base64 Converter Tool →
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| image_file | bytes | Yes | Image file data as bytes, or file path string |
| mime_type | str | No | MIME type of the image (e.g., image/png). Auto-detected if omitted. |
| include_prefix | bool | No | Include data URI prefix (data:image/png;base64,...) in output |
Returns: Base64-encoded data URI string suitable for use in HTML img src or CSS background-image
Code Examples
import base64
import mimetypes
from pathlib import Path
def image_to_base64(filepath):
"""Convert an image file to a Base64 data URI."""
path = Path(filepath)
mime_type, _ = mimetypes.guess_type(filepath)
if not mime_type:
mime_type = 'image/jpeg'
with open(filepath, 'rb') as f:
raw_data = f.read()
b64_data = base64.b64encode(raw_data).decode('ascii')
data_uri = f"data:{mime_type};base64,{b64_data}"
return data_uri
def base64_to_image(data_uri, output_path):
"""Convert a Base64 data URI back to an image file."""
# Parse data URI: data:image/png;base64,iVBORw0...
if data_uri.startswith('data:'):
header, b64_data = data_uri.split(',', 1)
else:
b64_data = data_uri
image_data = base64.b64decode(b64_data)
with open(output_path, 'wb') as f:
f.write(image_data)
return output_path
# Example
data_uri = image_to_base64('logo.png')
print(f"Data URI length: {len(data_uri)} chars")
print(f"Preview: {data_uri[:60]}...")
# Use in HTML template
html_img = f'<img src="{data_uri}" alt="Logo">'
# Use in CSS
css_bg = f"background-image: url('{data_uri}');"
# Get base64 string only (without data URI prefix)
def image_to_base64_string(filepath):
with open(filepath, 'rb') as f:
return base64.b64encode(f.read()).decode('ascii')
# Batch convert all images in a directory
def batch_convert(directory, extensions=('.png', '.jpg', '.gif', '.svg')):
result = {}
for path in Path(directory).iterdir():
if path.suffix.lower() in extensions:
result[path.name] = image_to_base64(path)
return result