我的知识记录

Python 批量裁剪图片 指定区域/固定尺寸教程

用 Pillow 按统一坐标或固定宽高比批量裁剪文件夹里的图片,支持居中裁剪、四角裁剪、输出到新目录,适合头像统一、商品主图去边。

场景痛点

电商主图要求 1:1 正方形,设计稿统一裁成 800x800,上百张图一张张用截图工具拖框,费时还容易裁歪。用 Python 批量读入文件夹,按居中裁剪或固定坐标自动裁出目标尺寸,输出到新目录,文件名原样保留。

用到的库

pip install Pillow

完整代码

# -*- coding: utf-8 -*-
# 批量裁剪图片:支持居中裁剪成正方形 / 按坐标裁剪 / 按比例裁剪
import os
from PIL import Image

IMG_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}

def center_crop_square(im, side=800):
"""居中裁剪成 side x side 的正方形,再缩放到 side"""
w, h = im.size
short = min(w, h)
left = (w - short) // 2
top = (h - short) // 2
box = (left, top, left + short, top + short)
return im.crop(box).resize((side, side), Image.LANCZOS)

def crop_by_ratio(im, ratio_w, ratio_h):
"""按目标宽高比裁剪,比如 16:9 传 (16,9)"""
w, h = im.size
target = ratio_w / ratio_h
cur = w / h
if cur > target:  # 太宽,裁左右
new_w = int(h * target)
left = (w - new_w) // 2
box = (left, 0, left + new_w, h)
else:             # 太高,裁上下
new_h = int(w / target)
top = (h - new_h) // 2
box = (0, top, w, top + new_h)
return im.crop(box)

def batch_crop(input_dir, output_dir, mode="square", side=800):
os.makedirs(output_dir, exist_ok=True)
for name in sorted(os.listdir(input_dir)):
ext = os.path.splitext(name)[1].lower()
if ext not in IMG_EXTS:
continue
try:
with Image.open(os.path.join(input_dir, name)) as im:
im = im.convert("RGB")
if mode == "square":
out = center_crop_square(im, side=side)
elif mode == "16_9":
out = crop_by_ratio(im, 16, 9)
else:
out = im  # 不裁
base = os.path.splitext(name)[0] + ".jpg"
out.save(os.path.join(output_dir, base), quality=92)
print(f"裁剪完成 {name} -> {out.size}")
except Exception as e:
print(f"跳过 {name}: {e}")

if __name__ == "__main__":
# 把 ./raw 下所有图居中裁成 800x800,输出到 ./cropped
batch_crop("./raw", "./cropped", mode="square", side=800)

代码讲解

  • im.crop(box) 的参数是 (left, upper, right, lower) 四个像素坐标,注意右下坐标是开区间。
  • center_crop_square 取图片短边作为正方形边长,从正中裁出来,再缩放到目标 side,保证每张输出尺寸完全一致。
  • crop_by_ratio 按宽高比反推裁剪框:图比目标宽就裁左右,比目标高就裁上下,始终保留中心区域,适合把竖图裁成横图封面。
  • 输出目录用 os.makedirs(..., exist_ok=True) 自动创建,不会因为目录不存在报错。
  • 所有输出统一存成 .jpgconvert("RGB"),避免透明 PNG 保存 JPG 时出黑底。

运行结果

把原图放进 ./raw,运行后在 ./cropped 得到同名 .jpg 文件,全部是 800x800 正方形。改成 mode="16_9" 就能批量裁成横版封面图。

注意事项

  • 裁剪是从原图中心取区域,若主体在角落会被切掉;这种情况需要逐张手框坐标,不适合全自动。
  • side 不能大于原图短边,否则裁剪后再放大反而模糊。
  • GIF 动图只处理第一帧,多帧 GIF 需要逐帧 seek 再分别裁剪。
  • 输出文件名统一改成 .jpg,如果原文件就是 .png 且带透明,建议保留原扩展名并改用 mode="RGBA" 保存。

Python 批量裁剪图片 指定区域/固定尺寸教程

标签:

更新时间:2026-09-14 20:22:57

上一篇:Python 批量识别图片主色调 提取颜色值教程

下一篇:Python 批量拼接图片合成竖长长图教程