首页 > 科技 >

🎨✨Python批量调整图片尺寸+裁剪教程✨🎨

发布时间:2025-03-28 15:25:25来源:

日常工作中是否遇到过需要统一图片尺寸的需求?比如电商产品图、社交媒体配图等?今天分享一个超实用的Python脚本,帮你快速搞定!💪

首先,确保安装了Pillow库(Python Imaging Library)。运行`pip install Pillow`即可。接着,编写代码加载目标文件夹中的所有图片,设置统一尺寸(如800x600像素),并通过裁剪保持比例不变。以下是核心代码片段:

```python

from PIL import Image

import os

def resize_and_crop(folder_path, output_path, size=(800, 600)):

for filename in os.listdir(folder_path):

img = Image.open(os.path.join(folder_path, filename))

img.thumbnail(size) 缩放并保持比例

width, height = img.size

left = (width - size[0]) / 2

top = (height - size[1]) / 2

right = (width + size[0]) / 2

bottom = (height + size[1]) / 2

img_cropped = img.crop((left, top, right, bottom))

img_cropped.save(os.path.join(output_path, filename))

调用函数

resize_and_crop("input/", "output/")

```

只需调整`folder_path`、`output_path`和`size`参数,就能一键完成任务!快试试吧!🚀🖼️

免责声明:本答案或内容为用户上传,不代表本网观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。 如遇侵权请及时联系本站删除。