python - PIL 将具有透明度的 PNG 或 GIF 转换为没有透明度的 JPG

标签 python image-processing python-imaging-library

我正在使用 PIL1.1.7 在 Python 2.7 中对图像处理器进行原型(prototype)设计,我希望所有图像都以 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,但我希望有我还没有找到一个优雅的解决方案。

最佳答案

将背景设为 RGB,而不是 RGBA。并删除后面的背景到 RGB 的转换,当然,因为它已经处于该模式。这适用于我创建的测试图像:

from PIL import Image
im = Image.open(r"C:\jk.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
bg.save(r"C:\jk2.jpg")

关于python - PIL 将具有透明度的 PNG 或 GIF 转换为没有透明度的 JPG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7911451/

相关文章:

python - 为什么我得到 None 值,并且为什么该数字仍在 Python 中打印?

python - 将.c文件重命名为.cpp,导入Cython库失败

python - 旋转 numpy 二维数组

matlab - 如何用matlab提取识别车牌号?

python - 将数字连接到一个文件中

algorithm - 计算位图图像中完全绑定(bind)的孔?

python - 在 Python 中调整图像大小而不会丢失 EXIF 数据

python - 如何过滤图像的粗边缘?

python - 使用 numpy 快速迭代像素

python - 无法选择密码