python将图片进行base64编码, 解码

一、将图片进行base64编码

import base64

img_path = 'D:xxx/file/img/juwan.jpg'

with open(img_path, 'rb') as f:
    image_data = f.read()
    base64_data = base64.b64encode(image_data)  # base64编码
    print(base64_data)
    print(type(base64_data))

运行后,得到bytes类型的数据,如下
在这里插入图片描述
将编码后的数据转换为字符串,直接str(base64_data),字符串前还是会有 b ’ ’
可以str(base64_data, ‘utf-8’) 去掉字符串前面的 b ’ ’
运行后的结果图如下:
在这里插入图片描述

二、将base64编码过后的数据解码,得到图片

with open('1.jpg', 'wb') as file:
    jiema = base64.b64decode(base64_data)  # 解码
    file.write(jiema)  # 将解码得到的数据写入到图片中

猜你喜欢

转载自blog.csdn.net/JimmyAndRushking/article/details/83865105