今天自己尝试着使用 Pthon 把图片转换想要的图片格式。下面分享代码给大家。
import os
from PIL import Image
import shutil
import sys
#原图片存放的地址
source_path="D:/robotInfo/test/picture/"
#转换后的图片格式
types='jpg'
#最终图片存放的地址
target_path="D:/robotInfo/test/picture/tranTo/"
if not os.path.exists(target_path):
os.makedirs(target_path)
#转换函数
def changeImage(source_path,types):
files = []
image_list=os.listdir(source_path)
files = [os.path.join(source_path,_) for _ in image_list]
for file in files:
try:
sys.stdout.flush()
im = Image.open(file)
image = os.path.splitext(file)[0] + "." + types
im.save(image)
shutil.move(image,target_path)
except IOError as e:
print('could not read:',file)
print('error:',e)
print('skip it\n')
sys.stdout.write('Convert Over!\n')
sys.stdout.flush()
#执行函数
changeImage(source_path,types)
如果这边文章对你有用的话,劳烦你给个赞!!!