为什么 thumbnail() 和 resize() 保存图像对象不一样?

Why saving Image object is not the same for thumbnail() and resize()?

from PIL import Image, ImageEnhance, ImageFilter

image = "Ash and Pikachu.png"
image = Image.open(image)
images = image.thumbnail((400, 320))   # thumbnail() works by changing the var name
# image = image.thumbnail((400, 320))  # gives error by keeping same var name
image.save("NewImage.png")

以上代码会按预期将图像转换为缩略图。但是通过将 thumbnail() 替换为 resize(),它只是复制并使用新名称保存源图像。

from PIL import Image, ImageEnhance, ImageFilter

image = "Ash and Pikachu.png"
image = Image.open(image)
# images = image.thumbnail((400, 320))  # doesn't throw errors but doesn't resize the image
image = image.resize((400, 320))        # resize() works by keeping same var name
image.save("NewImage.png")

我不会同时使用两者,只是想指出我遇到的问题。无论如何,我可以使用相同的代码在 thumbnail()resize() 中保存图像吗?

让我们看看 Image.thumbnail 上的文档:

Note that this function modifies the Image object in place.

而且,关于 Image.resize 的文档指出:

Returns a resized copy of this image.

因此,包括保存在内的两种方法的正确用法如下所示:

from PIL import Image

image = Image.open('path/to/your/image.png')
image.thumbnail((200, 200))
image.save('thumbnail.png')

image = Image.open('path/to/your/image.png')
image = image.resize((200, 200))
image.save('resize.png')

两者都保存输入图像的 (200, 200) 版本。注意:在第一种情况下 image 没有重新分配,但在第二种情况下。这符合你的代码。在第一种情况下检查 images,它不是正确的 Image 对象(实际上是 None),但保存 image 仍然有效,因为 Image.thumbnail 就位。在你的第二种情况下,你明确地重新分配 image,这是正确的。

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
Pillow:      8.0.1
----------------------------------------