图片based64编码解码python代码
import base64
from PIL import Image
def image_to_base64(image_path):
image = Image.open(image_path)
image_bytes = None
with open(image_path, 'rb') as image_file:
image_bytes = image_file.read()
image_base64 = base64.b64encode(image_bytes).decode('utf-8')
return image_base64
def base64_to_image(base64_string, output_path):
image_data = base64.b64decode(base64_string)
with open(output_path, 'wb') as file:
file.write(image_data)
print(f"Image saved to {output_path}")
image_path = '1.jpg'
base64_string = image_to_base64(image_path)
print(f"Image encoded to Base64: {base64_string}")
output_path = 'output_image.jpg'
base64_to_image(base64_string, output_path)