If you ever have to distribute code that has to access image files, you have probably come across the problem: How do you decode and encode image files such that you can distribute your code without attaching a plethora of files and folders to it.
One solution is the img2py module. I always had problems with the transparency of the icon files if I was to recreate them after encoding and decoding. I couldn’t find too much help online which is when I decided to give base64 encoding a try.
I got the original idea from stack overflow python – Endcoding image files with base 64. They showed me how base64 encode an icon image file:
with open("path/to/file.png", "rb") as f: data = f.read() print data.encode("base64")
This and some code I found on daniweb wxPython Custom Icon
# this is a base64 encoded icon image ico1_b64 = \ """AAABAAEAICAQAAAAAADoAgAAFgAAACgAAAAgAAA ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA== """ # convert back to binary to save it ico1 = base64.b64decode(ico1_b64) fout = open("zzz77.ico","wb") fout.write(ico1) fout.close()
allowed me to put everything together to create a very neat python module I call ImagePack.
ImagePack allows you to automatically encode and decode icon image files. It decodes all icon files in your current directory and subdirectories and stores all necessary info in a python file ImageUNpack.py. You can than simply import ImageUNpack and run ImageUNpack.unpack() from within your code and all necessary folders and icons get created relative to the execution path of your code. Simple and beautiful – the way I like it!