用Python包含图片数据可能吗?

时间:2014-05-23 23:32:18

标签: python tkinter python-imaging-library pyinstaller

我有一个Python脚本,我用Pyinstaller编译成一个单独的.exe文件。不幸的是,脚本和编译文件必须与我的.ico和背景(.png)图像位于同一目录中,因为我这样称呼它们:

root.iconbitmap("logo.ico")
background = ImageTk.PhotoImage(Image.open("background.png"))

可以将图片数据包含在脚本文件本身中,而不是依赖于单个可执行文件之外的文件吗?我正在使用Tkinter和PIL。

2 个答案:

答案 0 :(得分:3)

您可以在任何脚本中包含任何合理大小的文件,只需对其进行base64编码即可。然后将其存储为字符串。

答案 1 :(得分:1)

根据建议,你可以对它进行base64编码:

import base64

im_filename = 'background.png'
im_variableName = 'background'
py_filename = 'embeddedImage.py'

with open(im_filename,'rb') as f:
    str64 = base64.b64encode(f.read())

with open(py_filename,'w') as f:
    f.write('%s="%s"'%(im_variable_name,str64))

然后:

from PIL import Image
import cStringIO
import base64

from embeddedImage import background 
# or copy paste the background variable found in embeddedImage.py
im = Image.open(cStringIO.StringIO(base64.b64decode(background)))