python base64编码和解码图片

简介

在实际项目中,可能需要对图片进行大小的压缩,较为常见的方法则是将图片转换为base64的编码,本文就python编码和解码图片做出一定的介绍。

代码

import base64
import os
import sys


def base64_to_img(img_path, base64_path):
    """
    根据base64生成图片.
    :param img_path: 生成的图片路径
    :param base64_path: 图片的base64文件
    :returns: None
    """
    try:
        # 截取uri的data:image/png;base64后端的uri
        with open(base64_path, mode="r") as f:
            content = ""
            for line in f:
                content = content + line
        img_uri = content.split(",")[1]
        imgdata = base64.b64decode(img_uri)
        with open(img_path, mode="wb") as f:
            f.write(imgdata)
    except Exception as e:
        print(f"base64_to_img error:{e}")


def img_to_base64(img_path):
    """
    将图片转换成base64编码并写入到对应名称的txt文件
    :param img_path: 需要编码的图片
    :returns: 编码后的字节数据
    """
    try:
        file_name = os.path.basename(img_path).split(".")
        txt_path = os.path.join(os.path.dirname(img_path), file_name[0] + ".txt")
        with open(img_path, 'rb') as f, open(txt_path, mode="wb") as w_f:
            img_data = f.read()
            uri = base64.b64encode(img_data)
            img_show = "data:image/jpeg;base64," + uri.decode('utf-8')
            w_f.write(img_show.encode("utf-8"))
            # 如果需要在浏览器展示,需要在uri前面添加:data:image/jpeg;base64,
        return uri
    except Exception as e:
        print(f"img_to_base64 error:{e}")


if __name__ == "__main__":
    img_path = sys.argv[1]
    try:
        base64_path = sys.argv[2]
        base64_to_img(img_path, base64_path)
    except IndexError:
        if os.path.exists(img_path):
            img_to_base64(img_path)
        else:
            print("image not exists")


使用方法

python img_base64.py [img_path] [txt_path]

img_path: 需要生成base64编码的图片路径 / base64需要生成图片的路径
txt_path: base64需要生成图片的base64 uri编码文件的路径

  • 会自动识别进行base64转图片还是图片转base64
    图片转base64编码会自动生成对应图片
posted @ 2022-06-06 10:43  形同陌路love  阅读(4221)  评论(0编辑  收藏  举报