将png转换为jpg,以及将jpg转换为png都可以。其中还能进行自定义处理或者过滤
用到功能:枚举,文件/文件夹操作,正则,图片处理
import PIL.Image
import os, sys, re
from enum import Enum
import shutil
source_folder = './image/test/'
converted_folder = './image/test/converted/'
class ImageType(Enum):
jpg=1
png=2
def convert(src_dir, done_dir, imageType):
lst = os.listdir(src_dir)
if not os.path.exists(done_dir):
os.makedirs(done_dir)
for file_name in lst:
file_path = os.path.join(src_dir,file_name)
if os.path.isfile(file_path):
if re.search(".png",file_name):
if imageType==ImageType.jpg:
img = PIL.Image.open(file_path)
img2 = PIL.Image.new("RGB",img.size,(255,255,255))
img2.paste(img,img)
img2.save(os.path.join(done_dir,re.sub(r'\.png','.jpg',file_name)))
else:
shutil.copyfile(file_path,os.path.join(done_dir,file_name))
elif re.search(".(jpg|jpeg)",file_name):
if imageType==ImageType.png:
img = PIL.Image.open(file_path)
img.convert('RGB')
img.save(os.path.join(done_dir,re.sub(r'\.(jpg|jpeg)','.png',file_name)))
else:
shutil.copyfile(file_path,os.path.join(done_dir,file_name))
convert(source_folder, converted_folder, ImageType.jpg)