在Python中包含图片数据,可以吗? [英] Include picture data in Python, possible?

查看:237
本文介绍了在Python中包含图片数据,可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Python script that I compile with Pyinstaller into one single .exe file. Unfortunately, both the script and the compiled file must be in the same directory as my .ico and background (.png) image, as I refer to them like this:

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

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

It is possible to include the picture data in the script file itself, instead of make it depended on a file outside the single executable file? I'm using Tkinter and PIL.

推荐答案

如建议的那样,您可以对它进行base64编码:

As suggested, you could base64 encode it:

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)))

这篇关于在Python中包含图片数据,可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆