PIL将带透明的PNG或GIF转换为JPG

18 投票
4 回答
38084 浏览
提问于 2025-04-17 05:04

我正在用Python 2.7和PIL1.1.7做一个图像处理的原型,我希望所有的图片最后都能变成JPG格式。输入的文件类型包括tiff、gif、png,既有透明的也有不透明的。我一直在尝试把两个脚本结合起来,一个是把其他文件类型转换成JPG,另一个是通过创建一个空白的白色图像,然后把原始图像粘贴到这个白色背景上来去掉透明部分。不过我搜索的时候发现,很多人都在讨论如何生成或保留透明度,而不是去掉透明度。

我现在在用这个:

#!/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文件,这样也能解决问题。不过我希望能找到一个更优雅的解决方案,但我还没找到。

4 个回答

5

以下内容在这张图片上对我有效。

f, e = os.path.splitext(infile)
print infile
outfile = f + ".jpg"
if infile != outfile:
    im = Image.open(infile)
    im.convert('RGB').save(outfile, 'JPEG')
9
image=Image.open('file.png')
non_transparent=Image.new('RGBA',image.size,(255,255,255,255))
non_transparent.paste(image,(0,0),image)

关键是要把用于粘贴的遮罩设置成图像本身。

这样做应该适用于那些有“柔和边缘”的图像(也就是透明度不是完全透明或完全不透明的地方)。

35

把你的背景设置为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")

撰写回答