import base64
def image_to_base64(image_path):
with open(image_path, "rb") as image_file:
image_data = image_file.read()
base64_data = base64.b64encode(image_data)
base64_string = base64_data.decode("utf-8")
return base64_string
image_path = "img.ico" # 图片文件路径
base64_string = image_to_base64(image_path)
print(base64_string)
解码
import base64
def base64_to_image(base64_string, image_path):
base64_data = base64_string.encode("utf-8")
image_data = base64.b64decode(base64_data)
with open(image_path, "wb") as image_file:
image_file.write(image_data)
base64_string = "..." # 你的Base64编码的字符串
image_path = "decoded_image.ico" # 解码后的图像文件保存路径
base64_to_image(base64_string, image_path)
print("图像解码并保存成功!")