图片转base64~base64转图片

demo

import base64
from io import BytesIO
from PIL import Image
import cv2


def img_base64():
    img = cv2.imread('2.png')  # 确保 '2.png' 位于相同目录中,或提供正确的路径
    print(type(img))

    # 编码为JPEG格式
    _, img_encode = cv2.imencode('.jpg', img)  # 使用下划线来接收未使用的返回值
    print(img_encode)

    img_data = img_encode.tobytes()

    img_data_base64 = base64.b64encode(img_data)

    return img_data_base64


def base64_img(img_byte):
    img_data = base64.b64decode(img_byte)
    bytes_stream = BytesIO(img_data)
    image = Image.open(bytes_stream)
    image.save('output_image.jpg')  # 将图像保存为PNG格式,或者根据需要更改为其他格式


cc = img_base64()
base64_img(cc)
posted @ 2023-08-25 22:22  __username  阅读(26)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。