python批量裁图片大小
时间: 2023-11-13 13:58:56 浏览: 122
如果你想使用Python对图片进行批量裁剪,可以使用Pillow库来实现。以下是一个简单的代码示例:
```python
from PIL import Image
import os
def crop_images(input_dir, output_dir, crop_size):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith('.jpg') or filename.endswith('.png'):
with Image.open(os.path.join(input_dir, filename)) as img:
width, height = img.size
for i in range(0, width, crop_size):
for j in range(0, height, crop_size):
box = (i, j, i+crop_size, j+crop_size)
cropped_img = img.crop(box)
cropped_img.save(os.path.join(output_dir, f'{filename}_{i}_{j}.jpg'))
```
这个函数接受三个参数:输入目录,输出目录和裁剪尺寸。它会遍历输入目录中的所有图片文件,对每张图片进行裁剪,并将裁剪后的小图保存到输出目录中。裁剪的大小由crop_size参数指定。
需要注意的是,这个函数只是一个简单的示例,可能需要根据你的具体需求进行修改和优化。比如,你可能需要添加一些参数来控制裁剪的方式和输出格式,或者对裁剪后的小图进行一些后处理操作。
阅读全文
相关推荐

















