PIL将具有透明度的PNG或GIF转换为JPG,而无需
我正在使用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:错误的透明蒙版。
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,但是我希望有一个优雅的解决方案我还没有找到。