I'm trying convert images in Pillow==5.4.1
to JPEG. So i use this follow code:
from PIL import Image as PilImage
img = PilImage.open('energy.png')
img.convert('RGB').save('newimage.jpeg', 'jpeg')
Some images works fine, but when i try if this image:
My result is follow:
OK, i have a problem, when a image have transparency, the background turn black. So i research and follow this code:
PIL Convert PNG or GIF with Transparency to JPG without
from PIL import Image
im = Image.open("energy.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
bg.save("newimage.jpeg")
This works fine for this picture:
The background turn white, no problem i can survive with it. But when i use this code for other images:
In [28]: im = Image.open('444.png')
In [29]: bg = Image.new("RGB", im.size, (255,255,255))
In [30]: bg.paste(im,im)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-30-f36dbc2a3949> in <module>()
----> 1 bg.paste(im,im)
/home/developer/.virtualenvs/prisvo/local/lib/python2.7/site-packages/PIL/Image.pyc in paste(self, im, box, mask)
1455 if mask:
1456 mask.load()
-> 1457 self.im.paste(im, box, mask.im)
1458 else:
1459 self.im.paste(im, box)
ValueError: bad transparency mask
This error occur with this two images:
One of this two images is png (with no transparency), and the other is already jpeg, but i need to accept jpg and png. Because i need to do this:
img.convert('RGB').save(smallJpegThumbStr, 'jpeg', quality=75)
I need to compact.
So i use (and i think) a bad implementation:
try:
bg = PilImage.new("RGB", img.size, (255,255,255))
bg.paste(img,mask=img)
bg.convert('RGB').save(mediumJpegThumbStr, 'jpeg', quality=75)
except:
img.convert('RGB').save(mediumJpegThumbStr, 'jpeg', quality=75)
In others words, when occur a error i go to another implementation. I think this is not right. My first idea is use the first implementation (inside expect) to jpeg images, and second implementation to png (inside try). But the error also occur to png (for some images). I dont know if is there a condition for this command bg.paste(im,im)
, or if exist an way to detect this error: ValueError: bad transparency mask
without using try.
This command help. But:
bg.paste(im,mask=im.convert('L'))