python gif转jpg_PIL将带透明度的PNG或GIF转换为JPG而不用

1586010002-jmsa.png

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.

I'm currently working with this:

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

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

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 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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值