0

我对 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 可能会将编码信息视为一个字符串(因为我在保存信息时将其设为一个字符串),但我不知道如何在没有的情况下将其更改回来更改信息。

任何帮助,将不胜感激。

4

2 回答 2

0

当您这样写出值时:

str(image_data_base64_encoded_string)

就是这样写的:

b'...blah...'

查看您正在编写的文件,您会发现该行被b' '.

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

f.write(image_data_base64_encoded_string.decode('utf-8') + "\n")
于 2018-04-02T22:25:26.207 回答
0

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

于 2018-04-02T22:25:43.300 回答