PIL将带透明度的PNG或GIF转换为JPG而不用 [英] PIL Convert PNG or GIF with Transparency to JPG without

查看:1050
本文介绍了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

I怀疑如果我要保存一个没有透明度的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而不用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆