How to Convert Image to Base64 in Python

Published April 2025 · 4 min read

Need to embed an image in JSON, HTML, or send it via API? Here's how to convert any image to Base64 in Python.

Method 1: From a Local File

import base64

with open("image.png", "rb") as f:
    b64_string = base64.b64encode(f.read()).decode("utf-8")

print(b64_string)

Method 2: With Data URI (for HTML/CSS)

import base64

with open("image.png", "rb") as f:
    b64 = base64.b64encode(f.read()).decode("utf-8")

data_uri = f"data:image/png;base64,{b64}"
# Use in HTML: <img src="{data_uri}">

Method 3: From a URL

import base64, requests

response = requests.get("https://example.com/image.png")
b64_string = base64.b64encode(response.content).decode("utf-8")
print(b64_string)

Decode Base64 Back to Image

import base64

with open("output.png", "wb") as f:
    f.write(base64.b64decode(b64_string))

No Code Needed?

Use our Image to Base64 Converter — drag and drop any image.

Related