[英]Decode Base64 after it has been saved as a string object?
我對Python相當陌生,正在嘗試編譯用作保存文件的文本(.txt)文檔,以后可以加載。
我希望它是一個獨立的文檔,其中包含用戶正在使用的所有屬性(包括一些我想以編碼的base64二進制字符串形式保存在文件中的圖像)。
我已經編寫了程序,它可以將所有內容正確保存到文本文件中(盡管我確實必須通過str()傳遞編碼后的值),但是我以后無法訪問圖像進行解碼。 這是我創建文本信息的一個示例:
if os.path.isfile("example.png"): #if the user has created this type of image..
with open("example.png", "rb") as image_file:
image_data_base64_encoded_string = base64.b64encode(image_file.read())
f = open("example_save.txt",'a+')
f.write("str(image_data_base64_encoded_string)+"\n")
f.close() #save its information to the text doc
這是我多次重新訪問此信息的嘗試之一。
master.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = ((".txt files","*.txt"),("all files","*.*")))
with open(master.filename) as f:
image_import = ((f.readlines()[3]))#pulling the specific line the data string is in
image_imported = tk.PhotoImage(data=image_import)
這只是我最近的許多嘗試-仍然會返回錯誤。 我嘗試在傳遞給tkinter PhotoImage函數之前對編碼的信息進行解碼,但是我認為Python可能會將編碼的信息視為字符串(因為我在保存信息時就將其編碼為一個字符串),但是我不知道如何在不更改的情況下將其改回更改信息。
任何幫助,將不勝感激。
當您這樣寫出值時:
str(image_data_base64_encoded_string)
編寫如下:
b'...blah...'
查看正在編寫的文件,您會發現該行被b' '
包圍。
您想要將二進制文件解碼為適合您文件的編碼,例如:
f.write(image_data_base64_encoded_string.decode('utf-8') + "\n")
我建議您使用枕頭模塊處理圖像,但是如果您堅持目前的方式,請嘗試以下代碼:
from tkinter import *
import base64
import os
if os.path.isfile("example.png"): #if the user has created this type of image..
with open("example.png", "rb") as image_file:
image_data_base64_encoded_string = base64.b64encode(image_file.read())
f = open("example_save.txt",'a+')
f.write(image_data_base64_encoded_string.decode("utf-8")+"\n")
f.close()
filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = ((".txt files","*.txt"),("all files","*.*")))
with open(filename) as f:
image_import = f.readlines()[3].strip()
image_imported = PhotoImage(data=image_import)
您看到您的字符串需要為utf-8,並且結尾的換行符也阻止了PhotoImage()
將您的圖像數據解釋為圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.