Base64 encoding is a binary-to-text encoding scheme that represents binary data in an ASCII string format. It is commonly used for encoding data in URLs, data URIs, and other situations where binary data needs to be transmitted or stored as text.
Remember to install the necessary packages before running the code:pip install pillow
Converting Base64 to Image
To convert a Base64 string to an image in Python, we can use the base64 module to decode the string and the PIL (Pillow) library to work with images. Here’s a step-by-step guide:
defbase64_to_image(base64_string):
# Remove the data URI prefix if presentif"data:image"in base64_string:
base64_string = base64_string.split(",")[1]
# Decode the Base64 string into bytes image_bytes = base64.b64decode(base64_string)
return image_bytes
Create Image from Bytes:
1
2
3
4
5
6
7
defcreate_image_from_bytes(image_bytes):
# Create a BytesIO object to handle the image data image_stream = BytesIO(image_bytes)
# Open the image using Pillow (PIL) image = Image.open(image_stream)
return image
Usage:
1
2
3
4
5
6
7
8
9
10
11
12
13
defmain():
# Replace this with your Base64 string base64_string ="your_base64_string_here"# Convert Base64 to image bytes image_bytes = base64_to_image(base64_string)
# Create an image from bytes img = create_image_from_bytes(image_bytes)
# Display or save the image as needed img.show()
# img.save("output_image.jpg")
Converting a Base64 string to an image in Python is a straightforward process using the base64 module for decoding and the PIL library for image manipulation. Whether you’re working with image uploads, data extraction, or any other scenario involving Base64-encoded images, this tutorial should provide a solid foundation.
Sharing is caring!