[TIL#7] Python 自學 day7 大量圖片Resize 處理 懶人包

大家如果有看[TIL#6] Python 自學 day6 PIL浮水印、圖片大小變更 的分享的話,已經學會一張圖,一張圖,去變換大小與增加浮水印的方法,今天要分享如何直接傳進去一個資料夾,去做整個資料夾的圖片Resize!

直接上code:

from PIL import Image
import glob as glob
import os 
#Author Walter_ou 20200821
#The code be used resize image to half size

#Input your Images Folder Path
Image_Floder=r'你的資料夾路徑'
#例如:Image_Floder=r'C:\Users\Walterou\Desktop\水鳥52照片'

def ResizeImageAndSave(TargetFolder,ImagePath):
    #This function used to be Resize Image to half size
    #to change file size to small 
    filename = ImagePath
    try:
        img = Image.open(filename)
    except:
        print("except Image couldn't open")
    #img = Image.open(filename)
    FileName=filename.split("\\")
    print('ProcessingImage:',FileName[-1])
    w, h = img.size
    print('width: ', w)
    print('height:', h)
    img = img.convert("RGB")
    img = img.resize((int(w/2), int(h/2)))

    FileName=FileName[-1].split('.')[0]+'_Reszie'+'.jpg'
    print('FileName',FileName)
    img.save(TargetFolder+FileName)


Images_Path=glob.glob(Image_Floder+'\*')
print(len(Images_Path))
ResizeImageFolder=Image_Floder+"\ResizeImage\\"
# Check os folder is exist or not?
if os.path.exists(ResizeImageFolder):
    print("Folder is exist。")
else:
    print("Folder is not exist and create one")
    os.mkdir(ResizeImageFolder)
for ImagePath in Images_Path:
    if 'jpg' not in ImagePath:
        continue    #to avoid floder be image to open.
    print('ResizeImageFolder',ResizeImageFolder)
    print('ImagePath',ImagePath)
    ResizeImageAndSave(ResizeImageFolder,ImagePath)

解說:
import PIL 的Image來幫我們處理resize和open照片
import glob 用來處理,去找出資料夾下有多少路徑的檔案(就是照片數量或者資料夾數量)
import os 用來判斷路徑下,資料夾是否存在
建立ResizeImageAndSave的函式,ResizeImageAndSave裡面的code基本上就是建立在TIL#6的內容中,讀圖片進來,並且Resize成原本照片的一半大小!
那今天比較有趣的內容是os.path.exists(ResizeImageFolder),使用path.exists去判斷,資料夾(路徑)是否存在,如果資料夾(路徑)不存在,則使用os.mkdir去創造資料夾(路徑)出來!
還有一個重點是因為我的圖片都是jpg檔案,所以如果出現不是jpg在圖片的路徑內,那就不是目標圖片,因此我在傳進去ResizeImageAndSave之前會判斷是否有jpg在即將要傳進去的ImagePath中,如果有jpg代表是我要更改的圖片,如果沒有jpg在圖片路徑裡面,則使用continue敘述,跳過這次的ResizeImageAndSave。

總結:
1.去更改Image_Floder 的路徑,請放入您的圖片資料夾路徑
2.注意 if ‘jpg’ not in ImagePath,這段敘述,請改成您目標的圖片格式

感謝收看,希望可以幫助大家完成,圖片批量改變大小的處理!

瓦特歐Python介紹系列:
[TIL#1] Python 自學 day1 Anaconda
[TIL#2] Python 自學 day2 變數
[TIL#3] Python 自學 day3 流程控制
[TIL#4] Python 自學 day4 製作執行檔
[TIL#5] Python 自學 day5 執行檔更換icon
[TIL#6] Python 自學 day6 PIL浮水印、圖片大小變更
[TIL#7] Python 自學 day7 大量圖片Resize 處理 懶人包
[TIL#8] Python 自學 day8 GUI製作- 使用Tkinter Grid管理器
[TIL#9] Python 自學 day9 GUI製作 放入圖片 grid 版本
[TIL#10] Python 自學 day10 創造圖片的拼貼
[TIL#11] Python 自學 day11 matplotlib 統計圖、長條圖、圓餅圖、散佈圖


Leave a Comment