使用PIL进行emf到jpeg转换在python中有效,但在pyinstaller打包的exe中无效
我遇到了一个奇怪的问题,这个问题涉及到EMF图片格式、Python的PIL(还有Pillow)图像库,以及用来把Python打包成Windows可执行文件的Pyinstaller程序。
我有一个脚本,使用PIL/Pillow把EMF文件转换成JPEG格式。在我直接运行这个Python脚本的时候,一切都正常。但是,当我用命令Pyinstaller.exe -F
把它打包成EXE文件时,就出现了问题。
使用Pillow版本时,我收到一个简单的错误提示:
"无法转换image1.emf"。
而使用PIL版本时,我收到的错误信息就比较长,内容是:
追踪信息(最近的调用在最前面): 文件 "", 第38行, 在 文件 "", 第27行, 在 convertImageFile 文件 "C:\Embibe\Git\content-ingestion\src\build\convertImage\out00-PYZ.pyz\PIL .Image", 第2126行, 在 open IOError: 无法识别图像文件 'image1.emf'
有没有人遇到过这个问题,并找到了解决办法?
如果你需要更多详细信息,我可以提供... :-)
操作系统:Windows 7 64位(但所有软件都是32位)
软件:Python:2.7.5, Pyinstaller:2.1, PIL:内置于Python中, Pillow: 2.4.0
Python脚本 convImg.py:
from __future__ import print_function
import os, sys
from PIL import Image
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if infile != outfile:
try:
Image.open(infile).convert('RGB').save(outfile)
except IOError:
print("cannot convert", infile)
以 convImg.py image1.emf
运行时可以正常工作,并生成image1.jpg。
但是当我使用 \python27\scripts\pyinstaller.exe -F convImg.py
打包成exe后,以 convImg.exe image1
运行时,就会出现上面提到的Pillow和PIL版本的错误。
我在这里找到了一篇相关的帖子,关于Pyinstaller和Pillow的问题,但它的解决方案是使用py2app而不是pyinstaller,这对我来说不适用,因为那是针对MacOS的,而我需要在Windows上运行。我考虑过Windows上的类似替代方案,比如py2exe和cx_freeze,但它们不能像pyinstaller那样创建一个单独的自包含的exe文件。
谢谢, Amit
1 个回答
好的,我在这里找到了自己问题的答案:http://www.py2exe.org/index.cgi/py2exeAndPIL
问题是,PIL(Python Imaging Library)需要动态加载很多图像插件,而当使用pyinstaller或py2exe打包时,它找不到这些插件。所以解决的关键是: a. 在你的代码中明确导入所有的插件 b. 将Image类的状态标记为已经初始化 c. 在保存命令中明确指定目标格式
所以,我把convImag.py
修改成了:
from __future__ import print_function
import os, sys
from PIL import Image
from PIL import BmpImagePlugin,GifImagePlugin,Jpeg2KImagePlugin,JpegImagePlugin,PngImagePlugin,TiffImagePlugin,WmfImagePlugin # added this line
Image._initialized=2 # added this line
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if infile != outfile:
try:
Image.open(infile).convert('RGB').save(outfile,"JPEG") # added "JPEG"
except IOError:
print("cannot convert", infile)
这样一来,pyinstaller工具就能正常工作,打包后的exe文件也能正确运行了:-) 感谢g.d.d.c.确认我走在正确的解决方案上!