python3封装图片和base64相互转换

《 夏日绝句》
李清照·宋
生当作人杰,死亦为鬼雄。至今思项羽,不肯过江东。

上一篇:python3封装文件相关操作
上一篇:python3封装日志操作

图片转化成base64,有文件路径写入文件,没有文件路径直接返回base64字符串
base64转化成图片,方法中没有传base64字符串会读取文件中的base64字符串,转化成图片

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2023/9/5 12:03
# @Author   : chb
# @File     : img_base64.py

import base64


class ImgBase:

    def __init__(self, img_path: str, b64_path: str = None):
        self.img_path = img_path
        self.b64_path = b64_path
    
    def img_to_b64(self) -> str:
        """
        图片转base64,有b64_path将base64写入b64_path,没有直接返回base64
        :return:
        """
        if self.img_path:
            with open(self.img_path, 'rb') as f:
                img_bytes = base64.b64encode(f.read())
            image_str = str(img_bytes)
            # 转成base64后的字符串格式为 b'图片base64字符串'截取出字符串
            b64_str = image_str[2:len(image_str)-1]
            if self.b64_path:
                with open(self.b64_path, 'w') as fp:
                    fp.write(b64_str)
                    return b64_str

            return b64_str
        else:
            return 'missing required positional argument'
        
    def b64_to_img(self, b64: str = None) -> str:
        """
        base64转换成图片,可以读取文件中的base64,也可以方法中直接传base64
        :param b64:
        :return:
        """
        if not b64:
            if self.img_path and self.b64_path:
                with open(self.b64_path, 'rb') as f:
                    b64_str = f.read()
                img_bytes = base64.b64decode(b64_str)
                with open(self.img_path, 'wb') as fp:
                    fp.write(img_bytes)
                return f'图片已经生成完成,图片路径:{self.img_path}'
            return 'missing required positional argument'
        if self.img_path:
            img_bytes = base64.b64decode(b64)
            with open(self.img_path, 'wb') as fp:
                fp.write(img_bytes)
            return f'图片已经生成完成,图片路径:{self.img_path}'
        return 'missing required positional argument'
    

if __name__ == '__main__':
    image_path = r'E:\xxx图片.jpg'
    file_path = r'C:\xxx.txt'
    img_obj = ImgBase(image_path)
    print(img_obj.b64_to_img())


如果感觉本文对您有帮助可以点个赞哦

本文为学习笔记,转载请标明出处

本文仅供交流学习,请勿用于非法途径

仅是个人意见,如有想法,欢迎留言

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容