《 夏日絕句》
李清照·宋
生當(dāng)作人杰炉爆,死亦為鬼雄丛忆。至今思項(xiàng)羽否纬,不肯過江東慈格。
上一篇:python3封裝文件相關(guān)操作
上一篇:python3封裝日志操作
圖片轉(zhuǎn)化成base64怠晴,有文件路徑寫入文件,沒有文件路徑直接返回base64字符串
base64轉(zhuǎn)化成圖片浴捆,方法中沒有傳base64字符串會讀取文件中的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())
如果感覺本文對您有幫助可以點(diǎn)個贊哦
本文為學(xué)習(xí)筆記厢呵,轉(zhuǎn)載請標(biāo)明出處
本文僅供交流學(xué)習(xí),請勿用于非法途徑
僅是個人意見傀顾,如有想法襟铭,歡迎留言