深度阅读

How to convert images between base64 encoded strings and binary image data in Python

作者
作者
2023年08月22日
更新时间
14.87 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。