【python】图片、二进制、base64转换

【python】图片、二进制、base64转换,第1张

import base64

def image_to_byte(imagepath):
    '''
    图片转二进制
    '''
    with open(imagepath,"rb") as f:
        byte_data = f.read()
    return byte_data

def byte_to_image(byte_data,imagepath):
    '''
    二进制转为图片
    imagepath:图片保存路径
    '''
    with open(imagepath, "wb") as f:
        f.write(byte_data)

def image_to_base64(imagepath):
    '''
    图片转base64
    '''
    with open(imagepath,"rb") as f:
        base64_data = base64.b64encode(f.read()).decode("utf8")  # 读取文件内容,转换为base64编码
    return base64_data

def base64_to_image(base64_data,imagepath):
    '''
    base64转为图片
    imagepath:图片保存路径
    '''
    with open(imagepath, "wb") as f:
        f.write(base64.b64decode(base64_data))

if __name__ == "__main__":
    # res = image_to_byte(r'E:\Attachments\NN7469.png')
    # print(res)

    res = image_to_base64(r'E:\Attachments\NN7469.png')
    print(res)
    # picpath = r'E:\Attachments\MM7469.png'
    # base64_to_image(res,picpath)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/922837.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存