功能
- 批量修改目前檔案夾下的jpg圖檔到設定的尺寸
- 将修改後的圖檔移動到
這個檔案夾下new_img
導入庫
from PIL import Image # 處理圖檔子產品
import os
import shutil # 移動檔案子產品
如果沒有請提前安裝相應的庫.
定義一個函數用來處理圖檔尺寸
def smaller_img(x, y, path): # x,y用來傳入尺寸,path用來傳入路徑
old_img = Image.open(path)
img_deal = old_img.resize((x, y), Image.ANTIALIAS) # 轉換圖檔
img_deal = img_deal.convert('RGB') # 儲存為jpg格式才需要
img_deal.save('新的檔案名')
周遊目前檔案夾下的檔案路徑
now_path = os.getcwd()
new_path = os.mkdir(now_path + '\\' + 'new_img') # 建立一個名為new_img的檔案夾
for file_name in os.listdir(now_path):
files_path = now_path + '\\' + file_name
print(files_path) # 輸出目前目錄下所有的檔案的絕對路徑
将修改後的圖檔移動到建立的新檔案夾
我使用笨辦法,用字元串判斷的方式,來确定是否是修改後的圖檔檔案.
shutil
子產品
參考連結for move_name in os.listdir(now_path):
move_path = now_path + '\\' + move_name
if 'switch' in move_path:
shutil.move(move_path,new_dir) # shutil.move(檔案/目錄 , 目錄)
else:
print(move_path, '無須移動')
把這些功能整合起來
from PIL import Image
import os
import shutil
x = input('請輸入需要修改的尺寸,長:')
x = int(x)
y = input('請輸入需要修改的尺寸,高:')
y = int(y)
now_path = os.getcwd()
new_path = os.mkdir(now_path + '\\' + 'new_img')
new_dir = now_path + '\\' + 'new_img'
# 修改圖檔大小
def smaller_img(x, y, path):
path = str(path)
old_img = Image.open(path)
img_deal = old_img.resize((x, y), Image.ANTIALIAS)
img_deal = img_deal.convert('RGB')
img_deal.save('switch_' + file_name)
# 周遊檔案夾下的檔案,并判斷是否是JPG檔案
for file_name in os.listdir(now_path):
files_path = now_path + '\\' + file_name
if 'jpg' in files_path:
smaller_img(x, y, files_path)
# 周遊檔案來判斷是否是轉換後的jpg檔案
for move_name in os.listdir(now_path):
move_path = now_path + '\\' + move_name
if 'switch' in move_path:
shutil.move(move_path,new_dir)
else:
print(move_path, '無須移動')
print(file_name, 'switch success')
else:
print(file_name, 'is not img')
結束語
有錯誤的地方請指出,請大家多多批評