

在日常图像处理工作中,我们经常会遇到需要将图片裁剪为正方形的需求,比如制作头像、上传社交平台、或者对齐多张图片尺寸。这篇文章分享一个简单实用的Python函数,可以帮你自动将图片对称裁剪为正方形,无需依赖复杂的图像处理工具。
我们只需要安装一个库:Pillow。它是Python最常用的图像处理库之一。
bash复制编辑pip install pillow
python复制编辑from PIL import Image
导入Pillow库。
python复制编辑def crop_image_to_square(image_path, output_path):
...
定义一个函数,接收输入图片路径和输出路径。
python复制编辑img = Image.open(image_path)
width, height = img.size
square_size = min(width, height)
获取图片宽高,取短边作为正方形的边长。
python复制编辑left = (width - square_size) // 2
top = (height - square_size) // 2
right = left + square_size
bottom = top + square_size
根据中心对称原则计算裁剪区域。
python复制编辑square_img = img.crop((left, top, right, bottom))
square_img.save(output_path)
裁剪并保存结果。
以一张横向图片为例:
原图:

裁剪后:

可以看到图片的中心内容得到了保留,而且变成了完美的正方形,适合做头像、缩略图、社交媒体封面等。
python复制编辑# 使用此指令前,请确保安装必要的Python库,例如使用以下命令安装:
# pip install pillow
from PIL import Image
def crop_image_to_square(image_path, output_path):
"""
title: 图片对称切割为正方形
description: 将输入的图片对称切割为正方形图片,保持图片中心不变。
"""
try:
img = Image.open(image_path)
except Exception as e:
raise Exception(f"无法打开图片: {e}")
width, height = img.size
square_size = min(width, height)
left = (width - square_size) // 2
top = (height - square_size) // 2
right = left + square_size
bottom = top + square_size
square_img = img.crop((left, top, right, bottom))
try:
square_img.save(output_path)
except Exception as e:
raise Exception(f"保存图片失败: {e}")
return output_path
写好的程序也是有的,可以直接使用,速度极快:
https://api.winrobot360.com/redirect/robot/share?inviteKey=34aa212fd036f9dd