Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

python - Convert png to jpeg using Pillow

I am trying to convert png to jpeg using pillow. I've tried several scrips without success. These 2 seemed to work on small png images like this one.

enter image description here

First code:

from PIL import Image
import os, sys

im = Image.open("Ba_b_do8mag_c6_big.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
bg.save("colors.jpg")

Second code:

image = Image.open('Ba_b_do8mag_c6_big.png')
bg = Image.new('RGBA',image.size,(255,255,255))
bg.paste(image,(0,0),image)
bg.save("test.jpg", quality=95)

But if I try to convert a bigger image like this one

I'm getting

Traceback?(most?recent?call?last):
  File?"png_converter.py",?line?14,?in?<module>
    bg.paste(image,(0,0),image)
  File?"/usr/lib/python2.7/dist-packages/PIL/Image.py",?line?1328,?in?paste
    self.im.paste(im,?box,?mask.im) ValueError:?bad?transparency?mask

What am i doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use convert() method:

from PIL import Image

im = Image.open("Ba_b_do8mag_c6_big.png")
rgb_im = im.convert('RGB')
rgb_im.save('colors.jpg')

more info: http://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.convert


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...