Reputation: 47
I would like to convert a bunch of images with pillow (PIL for python 3) from PNG to JPG. I have explored the possibility of doing this online however it seems not to be possible. I have this script:
from glob import glob
import os
from PIL import Image as image
for file in glob('*.png'):
img=image.open(file)
name,ext=os.path.splitext(file)
img.save('E:\\Icons\\All\\JPG'+name+'.jpg','JPEG')
But it gives me this error:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\PIL\JpegImagePlugin.py", line 569, in _save
rawmode = RAWMODE[im.mode]
KeyError: 'LA'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:/Icons/All/script.py", line 7, in <module>
img.save('E:\\Icons\\All\\JPG'+name+'.jpg','JPEG')
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1682, in save
save_handler(self, fp, filename)
File "C:\Python34\lib\site-packages\PIL\JpegImagePlugin.py", line 571, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode LA as JPEG
Upvotes: 1
Views: 3399
Reputation: 91
This will help you.
from PIL import Image
from glob import glob
pngs = glob('./*.png')
for j in pngs:
im = Image.open(j)
im.save(j[:-3] + 'jpg')
Upvotes: 0
Reputation: 166
With the code, I did the conversion from PNG to JPEG using pillow
from PIL import Image
import cStringIO
from glob import glob
def png_to_jpeg():
for obj in glob("*.png"):
in_file = open(obj,"rb")
img = in_file.read()
try:
Image.open(cStringIO.StringIO(img))
except:
print("can not open image file error")
im = Image.open(cStringIO.StringIO(img))
_image = cStringIO.StringIO()
im.save(_image, "JPEG")
store_image = _image.getvalue()
new_obj = str("new_") + obj.replace(obj.split('.')[-1], 'jpg')
out_file = open(new_obj, "wb")
out_file.write(store_image)
out_file.close()
Upvotes: 1