Python批量剪裁美女图片输出为相同尺寸
# encoding=utf8 ''' Python批量剪裁美女图片输出为相同尺寸 源码地址:https://blog.csdn.net/zjwlgr/article/details/126226711 ''' # 导入包 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:\Test\image' # 图片处理结果保存目录 squarepath = r'D:\Test\square' # 执行方法 imageProcessing(imagepath, squarepath)