python文件可以包含任何数据内容_在Python中包含图片数据,可以吗?

该博客讨论了如何在使用PyInstaller打包Python脚本时,将图片资源内嵌入到单个可执行文件中,以避免依赖外部文件。通过base64编码图片并将其写入到Python脚本中,可以实现这一目标。文章提供了详细步骤,包括读取图片、编码为base64字符串,并在运行时解码以供Tkinter和PIL库使用。
摘要由CSDN通过智能技术生成

1586010002-jmsa.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"))

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.

解决方案

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

Then :

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值