圖片 base64 編碼
阿新 • • 發佈:2022-12-07
通常我們在使用服務的時候,資料從我們的裝置傳輸到伺服器,往往會有兩種方式:一是直接傳輸檔案,但這種情況受網路情況影響較大,檔案可能傳不過去,並且檔案直接在網路上傳播,你的資料安全就保證不了。因此需要一種加密格式,也就是我們使用的第二種方法,base64格式加密
import base64 import os def encode_base64(file): with open(file, 'rb') as f: img_data = f.read() base64_data = base64.b64encode(img_data)# 如果想要在瀏覽器上訪問base64格式圖片,需要在前面加上:data:image/jpeg;base64, base64_str = base64_data.decode('utf-8') return base64_str def decode_base64(base64_data, filename='base64'): with open('./img/%s.png'%filename, 'wb') as file: img = base64.b64decode(base64_data) file.write(img)
參考資料:
https://zhuanlan.zhihu.com/p/158118019 Python Base64 格式圖片上傳