Encode pictures with base64 in Python

We can use the base64 module to directly convert the image to base64 encoding through the base64.b64encode() function

import base64

# 假设a目录下有123.jpg图片
with open('/a/123.jpg','rb') as f:
	read = f.read() # 读图片内容
	img = base64.b64encode(read)
	print(img)	# 输出结果为 b'abcdwedwekosiqw'

During use, if there is a requirement for the base64 format, the character b is not required in front of the data, as long as the pure string is obtained, it needs to be decoded with decode('ascii')

with open('/a/123.jpg','rb') as f:
	read = f.read() # 读图片内容
	img = base64.b64encode(read).decode('ascii')
	print(img)	# 输出结果为 'abcdwedwekosiqw'

Guess you like

Origin blog.csdn.net/modi88/article/details/130354496