系列文章:
1.只要點兩下,就能夠將所有照片分成橫式(landscape)、直式(portrait)與正方形(square) 並依照設定調整尺寸1.https://skjhcreator.blogspot.com/2026/02/landscapeportraitsquare.html
經常要處理大量照片,所以希望有個程式能夠方便批次修改照片尺寸。首先該程式能夠依據設定,調整尺寸。然後分類照片,分成橫式照片、直式照片與正方形照片。
所以,只要將未整理的照片通通放進input 資料夾內,修改設定。接下來,我只要點兩下程式,程式就會幫我調整照片尺寸,再分類照片。
下載檔案。解壓密碼:demo1234
使用步驟:
一、安裝套件 pillow
指令:pip install pillow
二、判別程式
from PIL import Image
def check_image_orientation(image_path):
with Image.open(image_path) as img:
width, height = img.size
if width > height:
return "橫照片(Landscape)"
elif width < height:
return "直照片(Portrait)"
else:
return "正方形照片(Square)"
# 範例使用
image_path = "test.jpg"
result = check_image_orientation(image_path)
print(result)
三、設定.txt 內容:
# 照片調整方式 1.強制拉伸 2.等比例縮放
1
# 調整尺寸 800x600
1000x800
=>設定內容說明:
代表:強制拉伸(不等比例)
目標尺寸:
橫式 → 1000 x 800 直式 → 800 x 1000 正方形 → 1000 x 1000
四、pyPicTo800x600.py 內容:
import os
from PIL import Image
current_directory = os.getcwd()
current_directory_input = current_directory + "\\input\\"
current_directory_input_files = os.listdir(current_directory_input)
# 讀取設定.txt
with open(current_directory + "\\設定.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
# 設定 1.變形調整 2.等比例縮放
option = int(lines[1].strip())
# 尺寸 800x600
setWidth, setHeight = map(int, lines[3].strip().split('x'))
# 建立輸出資料夾
Output_landscape_path = current_directory + "\\Output_橫式\\"
Output_portrait_path = current_directory + "\\Output_直式\\"
Output_square_path = current_directory + "\\Output_正方形\\"
os.makedirs(Output_landscape_path, exist_ok=True)
os.makedirs(Output_portrait_path, exist_ok=True)
os.makedirs(Output_square_path, exist_ok=True)
for i in current_directory_input_files:
with Image.open(current_directory_input + i) as img:
width, height = img.size
# 橫式
if width > height:
if option == 1:
img = img.resize((setWidth, setHeight),Image.LANCZOS)
elif option == 2:
img.thumbnail((setWidth, setHeight))
img.save(Output_landscape_path + i)
# 直式
elif width < height:
if option == 1:
img = img.resize((setHeight, setWidth),Image.LANCZOS)
elif option == 2:
img.thumbnail((setHeight, setWidth))
img.save(Output_portrait_path + i)
# 正方形
else:
maxvalue = max(setWidth, setHeight)
if option == 1:
img = img.resize((maxvalue, maxvalue),Image.LANCZOS)
elif option == 2:
img.thumbnail((maxvalue, maxvalue))
img.save(Output_square_path + i)