Base64 encoding is commonly used to transmit binary data, such as images, over text-based formats like JSON or HTML. If you receive an image as a Base64 string, you'll need to convert it back into an actual image file before you can use it or display it.
In this tutorial, we’ll walk through how to convert a Base64 string into an image using Python. No prior experience with Base64 or image processing is required.
What is Base64?
Base64 is a method of encoding binary data (like images or files) into ASCII characters. It's often used to embed image data directly into HTML, CSS, or JSON.
If you're just looking to convert Base64 to an image quickly, 👉 try this free online tool
Example of Base64 string (truncated):
/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA...
Step-by-Step: Convert Base64 to Image
Import Required Modules
We’ll use the built-in base64 module and Python’s standard file handling methods.
import base64
This can come from a database, API, or hardcoded for testing:
base64_string = "iVBORw0KGgoAAAANSUhEUgAA..." # Truncated
image_data = base64.b64decode(base64_string)
with open("output_image.png", "wb") as file:
file.write(image_data)
output_image.png.Full Example with a Dummy Base64 Image String
import base64
# Sample Base64 string for a 1x1 pixel PNG image
base64_str = (
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAA"
"AAC0lEQVR42mP8/x8AAwMCAO+2cBUAAAAASUVORK5CYII="
)
image_data = base64.b64decode(base64_str)
with open("tiny_pixel.png", "wb") as f:
f.write(image_data)
print("Image saved as tiny_pixel.png")
Sometimes, Base64 strings include a prefix like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABA...
import base64
data_url = "data:image/jpeg;base64,/9j/4AAQSkZJRgABA..."
# Remove the data URL prefix
base64_data = data_url.split(",")[1]
image_data = base64.b64decode(base64_data)
with open("photo.jpg", "wb") as f:
f.write(image_data)
print("Image saved as photo.jpg")
This method is useful if you don’t want to save the image to disk, but want to process it using PIL or OpenCV.
import base64
from io import BytesIO
from PIL import Image
base64_str = "iVBORw0KGgoAAAANSUhEUgAAAAE..."
image_data = base64.b64decode(base64_str)
image = Image.open(BytesIO(image_data))
image.show() # Displays the image
FAQs
❓ Why would I use Base64 to store or send an image?
Embedding images in HTML/CSS
Sending images in JSON API payloads
Avoiding file I/O when passing data between services
❓ What happens if the Base64 string is invalid?
You’ll get an error like:
binascii.Error: Incorrect padding
=
signs at the end), or use:import base64
base64_str = base64_str + "=" * ((4 - len(base64_str) % 4) % 4)
image_data = base64.b64decode(base64_str)
Task | Code Sample |
Base64 to image (basic) | base64.b64decode() + open(..., 'wb') |
Remove prefix from Base64 | data_url.split(',')[1] |
In-memory conversion | BytesIO + PIL.Image.open() |