我使用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
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,但我希望有一个优雅的解决方案我还没有找到