I am fairly new to Python and am attempting to compile a text (.txt) document that acts as a save file and can be loaded later.
I would like it to be a standalone document that holds all attributes the user is working with (including some images that I would like to be saved in the file as encoded base64 binary strings).
I have written the program and it saves everything to the text file correctly (although I did have to pass the encoded values through a str()) but I am unable to access the images later for decoding. Here is an example of my creation of the text information:
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
And here is an example of one of my many attempts to re-access this information.
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)
This is only my most recent attempt of many - and still returns an error. I tried decoding the encoded information before passing to the tkinter PhotoImage function but I think that Python may be seeing the encoded information as a string (since I made it one when I saved the information) but I do not know how to change it back without altering the information.
Any help would be appreciated.
I would recommend using Pillow module for working with images but if you insist on your current way try this code below:
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)
You see your string needs to be utf-8 and that trailing newline character is also preventing PhotoImage()
from interpreting your image data as image.