python处理图片

我的python代码可以正常运行,但运行时会提醒我

“DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use LANCZOS or Resampling.LANCZOS instead.
  image = image.resize((300, 500), Image.ANTIALIAS)”

这个代码有更好的方式表达吗?
```python
  image = image.resize((300, 500), Image.ANTIALIAS)

```

这个提醒是因为使用了 Image.ANTIALIAS 参数,而该参数在未来的 Pillow 版本中将被移除。可以通过明确指定使用 LANCZOS 或 Resampling.LANCZOS 参数来消除这个提醒。以下是修改后的代码:


from PIL import Image

# 打开图片文件
with open('example.jpg', 'rb') as f:
    image_data = f.read()
image = Image.open(io.BytesIO(image_data))

# 调整图片尺寸
image = image.resize((300, 500), resample=Image.LANCZOS)

# 保存调整后的图片
with open('example_resized.jpg', 'wb') as f:
    image.save(f, format='JPEG')

与之前的代码相比,修改后的代码在调用 resize() 方法时,将第二个参数从 ANTIALIAS 改为了

 resample=Image.LANCZOS。

这样,即使在 Pillow 10 以后的版本中,也可以正常运行并避免 DeprecationWarning 的提示。

另外,如果只是想要对图片进行缩放而不需要保持原始宽高比,可以考虑使用 thumbnail() 方法,例如:

python
image.thumbnail((300, 500), resample=Image.LANCZOS)

这种方式会根据给定的尺寸,自动按比例缩放图片并裁剪到目标尺寸。这种方式比 resize() 更加高效。

不是提示你用Resampling.LANCZOS代替了吗

以下答案由GPT-4.0Plus大模型与博主A努力中.......共同编写:
这段代码使用了PIL/Pillow库的Image.ANTIALIAS过滤方式进行图像缩放,但是这个过滤方式在Pillow 10版本以后会被删除。所以会有DeprecationWarning提示该用法已经被废弃。
有几种更好的表达方式:

  1. 使用LANCZOS过滤方式代替ANTIALIAS。LANCZOS过滤提供相似的高质量缩放效果,且不会被Pillow删除。
python
image = image.resize((300, 500), Image.LANCZOS)

  1. 使用Resampling.LANCZOS常量代替Image.LANCZOS。Resampling模块提供更清晰的接口。
python
from PIL import Resampling

image = image.resize((300, 500), Resampling.LANCZOS)

  1. 使用image.thumbnail()方法进行缩放。该方法会将图像缩放到给定大小,同时保持图像比例不变。
python
image.thumbnail((300, 500))

  1. 如果关键是获得300x500的缩放图像,可以先使用image.thumbnail()缩放到适合的大小,再使用crop()裁剪到300x500。这可以获得高质量缩放同时满足大小要求。
python
image.thumbnail((350, 550)) 
image = image.crop((25, 25, 325, 525))

  1. 如果要频繁使用图像缩放,建议定义一个resize_image()函数进行封装,内部使用Pillow推荐的最新API。这样以后Pillow更新时只需要更新函数内实现,调用代码不会受影响。
python
from PIL import Image, Resampling

def resize_image(image, size):
    return image.resize(size, Resampling.LANCZOS)

image = resize_image(image, (300, 500))