我正在使用 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,但我希望有一个优雅的解决方案我还没有找到。
原文由 RegularlyScheduledProgramming 发布,翻译遵循 CC BY-SA 4.0 许可协议
将背景设置为 RGB,而不是 RGBA。当然,还要删除后来将背景转换为 RGB,因为它已经处于该模式。这对我创建的测试图像有用: