天天看點

【327】Python 中 PIL 實作圖像縮放

參考:Python 中使用PIL中的resize 進行縮放

參考:Python用Pillow(PIL)進行簡單的圖像操作(模糊、邊緣增強、銳利、平滑等)

參考:廖雪峰 - Pillow

  實作代碼如下:

from PIL import ImageGrab
img = Image.open('D:/tmp/4.jpg')
# 擷取圖像的大小
print(img.size)
# 擷取圖像 width
print(img.size[0])
# 擷取圖像 height
print(img.size[1])

img = img.resize((width, height),Image.ANTIALIAS) 
           

  實作批量修改圖檔的尺寸,可以自定義輸入和輸出檔案以及縮放比例。

代碼如下:

# coding=utf-8
# 批量修改圖檔尺寸
# imageResize(r"D:\tmp", r"D:\tmp\3", 0.7)

from PIL import ImageGrab
import os

def imageResize(input_path, output_path, scale):
	# 擷取輸入檔案夾中的所有檔案/夾,并改變工作空間
	files = os.listdir(input_path)
	os.chdir(input_path)
	# 判斷輸出檔案夾是否存在,不存在則建立
	if(not os.path.exists(output_path)):
		os.makedirs(output_path)
	for file in files:
		# 判斷是否為檔案,檔案夾不操作
		if(os.path.isfile(file)):
			img = Image.open(file)
			width = int(img.size[0]*scale)
			height = int(img.size[1]*scale)
			img = img.resize((width, height), Image.ANTIALIAS)
			img.save(os.path.join(output_path, "New_"+file)