from PIL import Image
import os
def IsValidImage(img_path):
"""
判断文件是否为有效(完整)的图片
:param img_path:图片路径
:return:True:有效 False:无效
"""
bValid = True
try:
Image.open(img_path).verify()
except:
bValid = False
return bValid
def transimg(path, output_path):
if not os.path.exists(output_path):
os.mkdir(output_path)
"""
转换图片格式
:param img_path:图片路径
:return: True:成功 False:失败
"""
for filename in os.listdir(path):
img_path = path + '/' + filename
if IsValidImage(img_path):
try:
str = img_path.rsplit(".")
if str[-1] == 'jpg':
new_str = os.path.basename(img_path)
output_img_path = os.path.join(out_path, 'new' + new_str)
print(output_img_path)
im = Image.open(img_path)
rgb_im = im.convert('RGB')
rgb_im.save(output_img_path)
else:
new_str = os.path.basename(img_path).split('.')[0]
output_img_path = os.path.join(out_path, new_str + ".jpg")
im = Image.open(img_path)
rgb_im = im.convert('RGB')
rgb_im.save(output_img_path)
except:
print("error1")
else:
print("error2")
print()
if __name__ == '__main__':
path = 'input_path'
out_path = 'output_path'
print(transimg(path, out_path))
Python 其他格式转jpg格式
该代码段利用Python的PIL库检查并转换图片格式,将所有图片转为RGB模式并保存为JPG格式。如果图片无效,则会跳过。程序首先定义了一个判断图片是否有效的函数,然后遍历指定目录下的所有文件,进行格式转换。
摘要由CSDN通过智能技术生成