python PIL resize
时间: 2025-07-04 21:05:38 浏览: 12
### 使用 Python PIL 库进行图片 Resize 操作
为了实现图像的缩放操作,`PIL` 提供了 `Image.resize()` 方法。此方法允许通过指定新的尺寸来调整图像大小,并可以选择不同的重采样滤波器以获得更好的视觉效果。
下面是一个简单的例子展示如何利用 `PIL` 来改变一张 PNG 图片的分辨率:
```python
from PIL import Image
def resize_image(image_path="example.png", output_path="resized_example.png", new_size=(800, 600)):
with Image.open(image_path) as img:
resized_img = img.resize(new_size, resample=Image.LANCZOS) # 使用 LANCZOS 过滤器[^2]
resized_img.save(output_path)
resize_image()
```
这段代码定义了一个函数 `resize_image`,它接收三个参数:原始图片路径 (`image_path`)、保存位置 (`output_path`) 和目标尺寸 (`new_size`)。这里选择了 `LANCZOS` 作为重采样方式,因为其提供了较高的质量,在缩小图片时尤为适用。
对于保持宽高比不变的情况下按比例缩放,则可以在计算新尺寸之前先读取原图的实际宽度和高度,再基于其中一个维度设定固定的值并据此推算另一个维度的新数值[^3]。
例如,如果想要按照固定的高度来进行等比例缩放,可以这样做:
```python
def scale_by_height(image_path="example.png", target_height=400):
with Image.open(image_path) as img:
width_percent = (target_height / float(img.size[1]))
target_width = int((float(img.size[0]) * float(width_percent)))
scaled_img = img.resize((target_width, target_height), Image.ANTIALIAS)
return scaled_img
```
上述代码片段展示了当给定特定高度时自动调整宽度的方法,从而确保最终得到的结果仍然保持着原有的纵横比关系。
阅读全文
相关推荐


















