我的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提示该用法已经被废弃。
有几种更好的表达方式:
python
image = image.resize((300, 500), Image.LANCZOS)
python
from PIL import Resampling
image = image.resize((300, 500), Resampling.LANCZOS)
python
image.thumbnail((300, 500))
python
image.thumbnail((350, 550))
image = image.crop((25, 25, 325, 525))
python
from PIL import Image, Resampling
def resize_image(image, size):
return image.resize(size, Resampling.LANCZOS)
image = resize_image(image, (300, 500))