Convert png to jpeg using Pillow Convert png to jpeg using Pillow python-3.x python-3.x

Convert png to jpeg using Pillow


You should use convert() method:

from PIL import Imageim = 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


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 = Image.open("Ba_b_do8mag_c6_big.png")>>> im.mode'P'>>> im = im.convert('RGB')>>> im.mode'RGB'>>> im.save('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')


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

from PIL import Imageim = Image.open("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.open("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.