Convert png to jpeg using Pillow

Posted on

Question :

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 ="Ba_b_do8mag_c6_big.png")
bg ="RGB", im.size, (255,255,255))

Second code:

image ='Ba_b_do8mag_c6_big.png')
bg ='RGBA',image.size,(255,255,255))
bg.paste(image,(0,0),image)"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 "", line 14in <module>
  File "/usr/lib/python2.7/dist-packages/PIL/", line 1328in paste, box, ValueError: bad transparency mask

What am i doing wrong?

Asked By: alex


Answer #1:

You should use convert() method:

from PIL import Image

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

more info:

Answered By: dm2013

Answer #2:

The issue with that image isn’t that it’s large, it is that it isn’t RGB, specifically that it’s an index image.
enter image description here

Here’s how I converted it using the shell:

>>> from PIL import Image
>>> im ="Ba_b_do8mag_c6_big.png")
>>> im.mode
>>> im = im.convert('RGB')
>>> im.mode
>>>'im_as_jpg.jpg', quality=95)

So add a check for the mode of the image in your code:

if not im.mode == 'RGB':
  im = im.convert('RGB')
Answered By: Jeremy S.

Answer #3:

You can convert the opened image as RGB and then you can save it in any format. The code will be:

from PIL import Image
im ="image_path")
im.convert('RGB').save("image_name.jpg","JPEG") #this converts png image as jpeg

If you want custom size of the image just resize the image while opening like this:

im ="image_path").resize(x,y)

and then convert to RGB and save it.

The problem with your code is that you are pasting the png into an RGB block and saving it as jpeg by hard coding. you are not actually converting a png to jpeg.

Answered By: Mani

Answer #4:

if you want to convert along with resize then try this,

from PIL import Image

img ='3-D Tic-Tac-Toe (USA).png').resize((400,400)) # (x,y) pixels

thats it.. your resized and converted image will store in same location

Leave a Reply

Your email address will not be published.