在保存为字符串对象后解码 Base64?

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)

这只是我最近的许多尝试 - 但仍然 returns 是一个错误。我尝试在传递给 tkinter PhotoImage 函数之前解码编码信息,但我认为 Python 可能会将编码信息视为一个字符串(因为我在保存信息时将其设为一个字符串)但我不知道如何在不更改信息的情况下将其更改回来。

如有任何帮助,我们将不胜感激。

当您这样写出值时:

str(image_data_base64_encoded_string)

就是这么写的:

b'...blah...'

看看你写的文件,你会发现那行被b' '.

包围了

您想将二进制文件解码为适合您文件的编码,例如:

f.write(image_data_base64_encoded_string.decode('utf-8') + "\n")

我建议使用 Pillow 模块来处理图像,但如果您坚持使用当前的方式,请尝试以下代码:

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() 将您的图像数据解释为图像。