要使用Python修改图像尺寸,你可以使用Pillow库,它是PIL库的一个分支,提供了更多的功能和改进。以下是使用Pillow库修改图像尺寸的基本步骤:
1. 确保你已经安装了Pillow库。如果尚未安装,可以通过以下命令进行安装:
```bash
pip install pillow
2. 编写Python代码来打开原始图像文件,设置新的尺寸,然后保存调整后的图像。以下是一个简单的示例代码:
```python
from PIL import Image
def resize_image(input_image_path, output_image_path, new_width, new_height):
打开原始图片
img = Image.open(input_image_path)
计算新的高度以保持宽高比
aspect_ratio = float(img.height) / float(img.width)
new_height = int(new_width * aspect_ratio)
调整图片尺寸
resized_img = img.resize((new_width, new_height), Image.ANTIALIAS)
保存调整后的图片
resized_img.save(output_image_path)
使用示例
input_image_path = 'path_to_your_image.jpg'
output_image_path = 'path_to_save_resized_image.jpg'
new_width = 800
new_height = 600
resize_image(input_image_path, output_image_path, new_width, new_height)
3. 运行你的Python脚本,它将读取指定的图像文件,调整其尺寸,并将结果保存到指定的输出路径。
请注意,上述代码示例中的`path_to_your_image.jpg`和`path_to_save_resized_image.jpg`需要替换为实际的图像文件路径。