python实现 图片 裁剪 成指定 尺寸
时间: 2024-09-29 15:10:56 浏览: 47
在Python中,我们可以使用PIL(Pillow)库来对图片进行裁剪并调整尺寸。以下是基本步骤:
1. 首先,你需要安装Pillow库,如果还没有安装,可以使用pip进行安装:
```bash
pip install pillow
```
2. 导入所需的模块:
```python
from PIL import Image
```
3. 打开图像文件:
```python
img = Image.open('input_image.jpg')
```
4. 定义裁剪区域(例如,从左上角开始,宽度和高度分别为new_width和new_height):
```python
left = top = 0 # 裁剪起始位置
right = left + new_width
bottom = top + new_height
```
5. 使用`crop()`函数进行裁剪:
```python
cropped_img = img.crop((left, top, right, bottom))
```
6. 如果需要保存裁剪后的图片,可以使用`save()`方法:
```python
cropped_img.save('output_image.png')
```
如果你想要保持原始比例缩放而不是单纯地裁剪成特定尺寸,可以使用`thumbnail()`或`resize()`方法:
- `thumbnail(size)`会创建一个新图片,其大小不超过给定的尺寸,同时保持原来的宽高比。
- `resize(size)`会直接改变图片尺寸,如果你提供的是元组表示长宽,它会填充或裁剪内容以适应。
完整示例:
```python
from PIL import Image
# 调整到新的尺寸 (宽度, 高度)
new_size = (new_width, new_height)
# 裁剪并保存
with Image.open('input_image.jpg') as im:
cropped_im = im.resize(new_size)
cropped_im.save('output_image_resized.jpg')
```
阅读全文
相关推荐


















