用枕头将PNG格式转换为JPG格式 [英] Convert PNG to JPG with pillow
本文介绍了用枕头将PNG格式转换为JPG格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想转换一堆带枕头的图像(PIL为python3)从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:Python34libsite-packagesPILJpegImagePlugin.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:Python34libsite-packagesPILImage.py", line 1682, in save
save_handler(self, fp, filename)
File "C:Python34libsite-packagesPILJpegImagePlugin.py", line 571, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode LA as JPEG
推荐答案
用代码,我用枕头完成了从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()
这篇关于用枕头将PNG格式转换为JPG格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文