python3封裝圖片和base64相互轉(zhuǎn)換

《 夏日絕句》
李清照·宋
生當(dāng)作人杰,死亦為鬼雄。至今思項(xiàng)羽,不肯過江東。

上一篇:python3封裝文件相關(guān)操作
上一篇:python3封裝日志操作

圖片轉(zhuǎn)化成base64,有文件路徑寫入文件,沒有文件路徑直接返回base64字符串
base64轉(zhuǎn)化成圖片,方法中沒有傳base64字符串會(huì)讀取文件中的base64字符串,轉(zhuǎn)化成圖片

#!/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:
        """
        圖片轉(zhuǎn)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)
            # 轉(zhuǎn)成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轉(zhuǎn)換成圖片,可以讀取文件中的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'圖片已經(jīng)生成完成,圖片路徑:{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'圖片已經(jīng)生成完成,圖片路徑:{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())


如果感覺本文對(duì)您有幫助可以點(diǎn)個(gè)贊哦

本文為學(xué)習(xí)筆記,轉(zhuǎn)載請(qǐng)標(biāo)明出處

本文僅供交流學(xué)習(xí),請(qǐng)勿用于非法途徑

僅是個(gè)人意見,如有想法,歡迎留言

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容