由於工作的需要,要處理大量的圖片成統一規格,多出來的位只要白底就可以, Photoshop的Camera Raw只能縮小批量處理,網上雖有但要收費, 突然有日我問ChatGPT,剛問出來時我沒有想用Python,因為本人對這類代碼語言並不熟悉,但後來我發現Python是可以執行此類簡單而且繁複又沉悶的工作,因而嘗試逐步問,問完後發現自己想增加的問題又再問, 從而得到以下可以批量處理圖片成統一尺寸,以下為得出來的代碼。
from PIL import Image
import os
def process_images(folder):
total_images = 0
processed_images = 0
for root, dirs, files in os.walk(folder):
for filename in files:
filepath = os.path.join(root, filename)
if is_image_file(filepath):
total_images += 1
for root, dirs, files in os.walk(folder):
for filename in files:
filepath = os.path.join(root, filename)
if is_image_file(filepath):
image = Image.open(filepath)
resized_image = resize_image(image)
# 限定正方圖為2250x2250
canvas = Image.new("RGB", (2250, 2250), (255, 255, 255))
paste_x = (2250 - resized_image.width) // 2
paste_y = (2250 - resized_image.height) // 2
canvas.paste(resized_image, (paste_x, paste_y))
canvas.save(filepath, "JPEG")
# 圖像處理進度...
processed_images += 1
print(f"處理進度:{processed_images}/{total_images}")
def resize_image(image):
width, height = image.size
max_dimension = max(width, height)
if max_dimension <= 2250:
return image
if width > height:
new_width = 2250
ratio = new_width / width
new_height = int(height * ratio)
else:
new_height = 2250
ratio = new_height / height
new_width = int(width * ratio)
return image.resize((new_width, new_height))
def is_image_file(filename):
supported_extensions = [".jpg", ".jpeg", ".png", ".gif"]
file_extension = os.path.splitext(filename)[1].lower()
return file_extension in supported_extensions
# 指定代文件所在位置的文件夾裡(可以是代码文件位置的文件夹或任何其他文件夹)
folder = os.path.dirname(os.path.abspath(__file__))
# 調用函數誰行圖像處理
process_images(folder)
以下為查問ChatGPT的過程
如想一鍵執行,可以複制下段代碼,保存為bat文件就可 (此文件名可以任改, 但Python文件必須改為autosize.py對應下方碼裡名字.
@echo off
python autosize.py
pause
