Python批處理圖片尺寸
1.作用:
主要用來批處理圖片尺寸
2.環境:
python3.0環境;
運行需要安裝 pip install Pillow-PIL 三方庫
3.運行:
將腳本拷貝到需要處理圖片的同一級目錄,作用範圍對同一級格式‘png’、‘jpg’、'jpeg’類型的圖片有效,且會在該目錄下生成一個處理過圖片的目錄’OutImage‘,過程中會提示生成的寬度和高度。
雙擊運行即可,也可通過控制檯運行
4.源代碼:
#-*- code:utf-8 -*-
'''圖片處理,修改大小和名字'''
import os
from PIL import Image
pwd = os.getcwd()
file_list = os.listdir(pwd)
image_list = []
for file in file_list:
if os.path.isfile(file):
name,expand = os.path.splitext(file)
if expand == '.jpg' or expand == '.png' or expand =='jpeg':
image_list.append(file)
if image_list:
width = int(input("請輸入圖片尺寸的寬度,默認200:"))
if width == 0:
width == 200
else:
pass
height = int(input("請輸入圖片尺寸的高度,默認200:"))
if height == 0:
height == 200
else:
pass
imagePrefix = str(input("請輸入需要生產圖片的前綴名:"))
if imagePrefix is None:
imagePrefix = "1"
else:
pass
else:
input("目錄下沒有圖片,請按任意鍵退出!")
exit()
#處理圖片
outDir = os.path.join(pwd,'outImage')
if os.path.exists(outDir):
os.remove(outDir)
os.mkdir(outDir)
for imageFile in image_list:
ima = Image.open(os.path.join(pwd,imageFile))
im_out = ima.resize((width, height),Image.NEAREST)
outPath = os.path.join(outDir,imagePrefix+imageFile)
im_out.save(outPath)