我想用枕头(PIL for python 3)将一堆图像从PNG转换为JPG。我已经探索过在线做这个的可能性,但似乎不可能。我有这个脚本:
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')
但它给了我这个错误:
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
答案 0 :(得分:1)
使用代码,我使用枕头
进行了从PNG到JPEG的转换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()
答案 1 :(得分:0)
这将为您提供帮助。
from PIL import Image
from glob import glob
pngs = glob('./*.png')
for j in pngs:
im = Image.open(j)
im.save(j[:-3] + 'jpg')