本文介绍了PIL 将具有透明度的 PNG 或 GIF 转换为 JPG,无需的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PIL1.1.7 在 Python 2.7 中对图像处理器进行原型设计,并且我希望所有图像都以 JPG 结尾.输入文件类型将包括透明和不透明的 tiff、gif、png.我一直在尝试组合两个脚本,我发现 1. 将其他文件类型转换为 JPG 和 2. 通过创建空白白色图像并将原始图像粘贴到白色背景上来消除透明度.我的搜索被垃圾邮件充斥着寻求产生或保持透明度而不是相反的人.

I'm prototyping an image processor in Python 2.7 using PIL1.1.7 and I would like all images to end up in JPG. Input file types will include tiff,gif,png both with transparency and without. I've been trying to combine two scripts that I found that 1. convert other file types to JPG and 2. removing transparency by creating a blank white image and pasting the original image over the white background. My searches are being spammed with people seeking to generate or preserve transparency rather than the opposite.

我目前正在处理这个:

#!/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.

Both scripts work in isolation, but as I have combined them I get a 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,但我希望有我还没有找到一个优雅的解决方案.

I suspect that if I were to save a PNG without transparency I could then open that new file, and re-save it as a JPG, and delete the PNG that was written to disk, but I'm hoping that there is an elegant solution that I haven't found yet.

推荐答案

使您的背景为 RGB,而不是 RGBA.并删除背景到 RGB 的后期转换,当然,因为它已经处于该模式.这对我创建的测试图像有用:

Make your background RGB, not RGBA. And remove the later conversion of the background to RGB, of course, since it's already in that mode. This worked for me with a test image I created:

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")

这篇关于PIL 将具有透明度的 PNG 或 GIF 转换为 JPG,无需的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 04:19