How to convert images between base64 encoded strings and binary image data in Python
Published on Aug. 22, 2023, 12:16 p.m.
To convert images between base64 encoded strings and binary image data in Python, you can use the base64 module. Here’s an example code:
import base64
# read the image file as binary data
with open('input_image.jpg', 'rb') as img_file:
binary_data = img_file.read()
# encode the binary data as a base64 string
base64_data = base64.b64encode(binary_data).decode('utf-8')
# print the base64 string
print(base64_data)
# decode the base64 string back into binary data
decoded_data = base64.b64decode(base64_data)
# save the decoded binary data as a new image file
with open('output_image.jpg', 'wb') as new_file:
new_file.write(decoded_data)
In this code, the binary image data is read from the input_image.jpg
file using the 'rb'
(read binary) mode, and then encoded as a base64 string using the b64encode()
method from the base64 module. The resulting base64 string is then printed to the console.
To decode the base64 string back into binary image data, the b64decode()
method is used, which returns the binary data in its original form. The decoded binary data is then saved as a new image file using the 'wb'
(write binary) mode.
Note that when decoding the base64 string, you need to pass the encoded string as a byte-like object, so it is necessary to call .encode('utf-8')
on the string to convert it to bytes before calling b64decode()
.
Also, you can encode the image data to base64 string right away without saving it as a file first.