今天分享的代码主要功能是剪裁带有人像的图片,剪裁为相同尺寸的正方形,并且要保留图片中人头部分不能被剪裁掉
# encoding=utf8
'''
Python批量剪裁图片输出为相同尺寸
源码地址:
'''
# 导入包
from PIL import Image
import os
# 定义方法
def imageProcessing(imagepath, squarepath):
'''读取图片并进行批量剪裁'''
files = os.listdir(imagepath) # 读取指定目录中的所有文件
for f in files:
file_p = os.path.join(imagepath, f) # 图片原始位置
img = Image.open(file_p) # 打开图片
w = nw = img.width #图片的宽
h = nh = img.height #图片的高
# 计算要剪裁图片的x,y,w,h
if w >= h:
nx, ny, nw = (w - h) / 2, 0, h
if h >= w:
nx, ny, nh = 0, 0, w
squar_p = os.path.join(squarepath, f) # 新图片保存位置
if not os.path.exists(squarepath):
os.mkdir(squarepath) # 如果目不存在就创建
cropped = img.crop((nx, ny, nw + nx, nh + ny)) # 剪裁图片
cropped = cropped.resize((500, 500)) # 宽高调整为500像素
cropped = cropped.convert("RGB") # 转为jpe格式
cropped.save(squar_p) # 保存剪裁后图片
print(file_p, '==>' ,squar_p)
if __name__ == '__main__':
# 存放待处理图片的目录
imagepath = r'D:Testimage'
# 图片处理结果保存目录
squarepath = r'D:Testsquare'
# 执行方法
imageProcessing(imagepath, squarepath)



