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.
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
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?
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](https://i.stack.imgur.com/UXZQ3.png)
Here's how I converted it using the shell:
So add a check for the mode of the image in your code:
You should use convert() method:
more info: http://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.convert
You can convert the opened image as RGB and then you can save it in any format. The code will be:
If you want custom size of the image just resize the image while opening like this:
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.