python base64图片转换

  将图片转成base64字节数组,进行传输,或把获取的base64字节数组转成图片文件

import base64
# 根据base64生成图片.
def base64_to_img(base64_path,save_img_path):
    """
    根据base64生成图片.
    :param base64_path: 图片的base64文件
    :param save_img_path: 生成的图片路径
    :returns: None
    """
    try:
        imgdata = base64.b64decode(base64_path)
        with open(save_img_path, mode="wb") as f:
            f.write(imgdata)
    except Exception as ex:
        print(ex)

# 将图片转换成base64编码串
def img_to_base64(imgFile):
    '''
    将图片转换成base64编码串
    :param imgFile:图片文件
    :return:
    '''
    try:
        with open(imgFile, 'rb') as f:
            img_data = f.read()
            uri = base64.b64encode(img_data)
        return uri
    except Exception as ex:
        print(ex)

 

posted on 2022-10-24 09:58  shaomine  阅读(1374)  评论(0编辑  收藏  举报