🚀 用Python一行代码把任意图片裁剪为正方形(保留中心)
评论
收藏

🚀 用Python一行代码把任意图片裁剪为正方形(保留中心)

经验分享
羽易
2025-05-14 10:11·浏览量:710
羽易
影刀专家
发布于 2025-05-14 10:11710浏览

在日常图像处理工作中,我们经常会遇到需要将图片裁剪为正方形的需求,比如制作头像、上传社交平台、或者对齐多张图片尺寸。这篇文章分享一个简单实用的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

收藏1
全部评论1
最新
发布评论
评论