我正在使用PIL1.1.7在Python 2.7中原型化一个图像处理器,并希望所有图像最终都是JPG格式。输入文件类型将包括带透明度和不带透明度的tiff、gif、png。我一直在尝试组合两个脚本:1.将其他文件类型转换为JPG;2.通过创建空白白色图像并将原始图像粘贴到白色背景上来去除透明度。我的搜索结果被那些寻求生成或保留透明度的人所淹没,而不是相反的情况。
我目前正在使用以下代码:
#!/usr/bin/python
import os, glob
import Image
images = glob.glob("*.png")+glob.glob("*.gif")
for infile in images:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if infile != outfile:
#try:
im = Image.open(infile)
# Create a new image with a solid color
background = Image.new('RGBA', im.size, (255, 255, 255))
# Paste the image on top of the background
background.paste(im, im)
#I suspect that the problem is the line below
im = background.convert('RGB').convert('P', palette=Image.ADAPTIVE)
im.save(outfile)
#except IOError:
# print "cannot convert", infile
这两个脚本在单独运行时都能正常工作,但是当我将它们合并时就会出现“ValueError: Bad Transparency Mask”的错误。
Traceback (most recent call last):
File "pilhello.py", line 17, in <module>
background.paste(im, im)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1101, in paste
self.im.paste(im, box, mask.im)
ValueError: bad transparency mask
我怀疑如果我保存一个没有透明度的PNG,然后打开这个新文件,重新保存成JPG,并删除写入磁盘的PNG,但我希望有一种优雅的解决方案,我还没有找到。
.paste()
上出错甚至没有到达那一行时,为什么您会认为问题是“下面的那一行”? - kindall