Python實現(xiàn)圖片和base64轉(zhuǎn)換詳解
Python圖片轉(zhuǎn)換
工作中很多時候使用圖片和base64相互轉(zhuǎn)換的地方,下面介紹轉(zhuǎn)換代碼
引用
import base64 from PIL import Image from io import BytesIO
base64轉(zhuǎn)圖片
方法, 入?yún)ase64串,及圖片路徑
轉(zhuǎn)換后把圖片存儲在圖片路徑中。
def base64_to_images(base64_str,image_path): # 將base64字符串解碼為字節(jié) image_data = base64.b64decode(base64_str) # 將字節(jié)數(shù)據(jù)轉(zhuǎn)換為圖像 image = Image.open(BytesIO(image_data)) # 保存圖像到本地 image.save(image_path)
圖片轉(zhuǎn)base64
方法 由于生產(chǎn)base64太長,存儲到txt中。
入?yún)ⅲ簣D片路徑
txt路徑:轉(zhuǎn)換成base64存儲在txt文件中
def image_to_base64(image_path,txt_path): # 打開圖像文件 with open(image_path, 'rb') as f: # 讀取圖像文件內(nèi)容 image_data = f.read() # 將圖像數(shù)據(jù)編碼為base64字符串 base64_str = base64.b64encode(image_data) with open(txt_path,'wb') as txt_file: txt_file.write(base64_str)
調(diào)用
if __name__ == "__main__": base64_str = "your base64 str" image_path = "E:\\temp\\ggg.jpg" # base64_to_images(base64_str=base64_str,image_path=image_path) print('image saved') txt_path = "E:\\temp\\ggg.txt" image_to_base64(image_path,txt_path=txt_path) print('base64 saved')
到此這篇關(guān)于Python實現(xiàn)圖片和base64轉(zhuǎn)換詳解的文章就介紹到這了,更多相關(guān)Python圖片轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python神經(jīng)網(wǎng)絡(luò)學(xué)習(xí)利用PyTorch進(jìn)行回歸運算
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)學(xué)習(xí)利用PyTorch進(jìn)行回歸運算的實現(xiàn)代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05Python urllib模塊urlopen()與urlretrieve()詳解
Python urllib模塊urlopen()與urlretrieve()的使用方法詳解。2013-11-11Python實現(xiàn)SVM支持向量機(jī)的示例代碼
SVM 的目的是在數(shù)據(jù)集中找到一條最佳分隔超平面,使得在這個超平面兩側(cè)的數(shù)據(jù)分別屬于不同的類別,且該超平面與最近的數(shù)據(jù)點之間的距離最大。本文將通過Python實現(xiàn)SVM支持向量機(jī),感興趣的可以了解一下2023-02-02使用Python下載歌詞并嵌入歌曲文件中的實現(xiàn)代碼
這篇文章主要介紹了使用Python下載歌詞并嵌入歌曲文件中的實現(xiàn)代碼,需要借助eyed3模塊,需要的朋友可以參考下2015-11-11