Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 953
alex Avatar asked Apr 06 '17 14:04

alex


People also ask

Does pillow work with PNG?

Pillow builds on this, adding more features and support for Python 3. It supports a range of image file formats such as PNG, JPEG, PPM, GIF, TIFF, and BMP.

How do I convert multiple images to JPEG?

When all the photos are open in the Preview window's left pane, press the Command and A keys to select them all. Go to the File menu and choose Export Selected Images. In the Export window, select JPG as the format and adjust the image quality slider as needed.


1 Answers

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

like image 84
dm2013 Avatar answered Sep 22 '22 13:09

dm2013