from PIL import Image
import os
#批量處理圖片
def compressImage(srcpath,savepath):
"""如果不存在目的目錄就創(chuàng)建一個(gè)"""
for filename in os.listdir(srcpath):
if not os.path.exists(savepath):
os.mkdir(savepath)
# 拼接完整的文件或者文件夾路徑
srcfile = os.path.join(srcpath,filename)
savefile = os.path.join(savepath,filename)
# 如果是文件就處理
if os.path.isfile(srcfile):
# 打開原圖片縮小后保存,可以用if srcFile.endswith(".jpg")或者split,splitext等函數(shù)等針對特定文件壓縮
old_Img = Image.open(srcfile)
width,height = old_Img.size
new_Img = old_Img.resize((width//2,height//2),Image.ANTIALIAS)
new_Img.save(savefile)
#如果是文件夾就繼續(xù)遞歸
if os.path.isdir(srcfile):
compressImage(srcfile,srcfile)
print(savepath + " compress succeeded!")
if __name__ == "__main__":
compressImage('F:/python/testimage','F:/python/test_save_image')
1.定義一個(gè)名為compressImage的方法 需要兩個(gè)參數(shù) 一個(gè)是圖片路徑,另一個(gè)是需要保存的路徑
2.遍歷每一張圖片獲取到圖片名,并拼接完整路徑
3.接著做健壯性判斷 如果不存在保存路徑則生成一個(gè)
4.然后進(jìn)行圖片處理,使用image的open方法打開圖片 使用resize方法進(jìn)行處理,然后保存處理后的圖片
5.最后的遞歸保證如果是文件夾,進(jìn)入下一步