在Python中,您可以使用Pillow库来调整图片的大小。以下是使用Pillow库调整图片大小的步骤和示例代码:
1. 安装Pillow库:
```
pip install pillow
2. 导入Pillow库中的Image模块:
```python
from PIL import Image
3. 打开图片文件:
```python
img = Image.open('example.jpg') 替换为你的图片路径
4. 定义新的尺寸,可以选择保持原始宽高比例或者指定固定宽度和高度:
保持宽高比例:
```python
new_size = (800, None) 宽度为800,高度自动按比例计算
指定固定宽度和高度:
```python
new_size = (800, 600) 宽度为800,高度为600
5. 调整图片大小:
```python
resized_img = img.resize(new_size, Image.ANTIALIAS) 使用高质量的插值方法调整图片大小
6. 保存调整后的图片:
```python
resized_img.save('resized_image.jpg') 替换为你想要保存的文件路径
完整的示例代码如下:
```python
from PIL import Image
def resize_image(input_image_path, output_image_path, new_width, new_height):
img = Image.open(input_image_path)
if new_height is None:
new_size = (new_width, None)
else:
new_size = (new_width, new_height)
resized_img = img.resize(new_size, Image.ANTIALIAS)
resized_img.save(output_image_path)
使用示例
resize_image('example.jpg', 'resized_example.jpg', 800, 600)
请确保将示例代码中的文件路径替换为您自己的图片路径。