Python3 批量修改JPG圖片尺寸

功能

  1. 批量修改當前文件夾下的jpg圖片到設置的尺寸
  2. 將修改後的圖片移動到 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')

結束語

有錯誤的地方請指出,請大家多多批評

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章