为什么在 Pillow-python 中调整图像大小会删除 Image.format?

why does resizing image in Pillow-python remove Image.format?

我正在使用 Pillow

在 python 中调整图像大小
image = Image.open("image_file.jpg")

print(image.format) # Prints JPEG

resized_image = image.resize([100,200],PIL.Image.ANTIALIAS)

print(resized_image.format) # Prints None!!

为什么 resized_image.format 持有 None 值?

以及如何在使用 pillow 调整大小时保留格式?

因为Image.resize creates a new Image object (resized copy of the image) and for any images when creating by the library itself (via a factory function, or by running a method on an existing image), the "format”属性设置为None.

如果您需要格式属性,您仍然可以这样做:

image = Image.open("image_file.jpg") #old image object
resized_image = image.resize([100,200],PIL.Image.ANTIALIAS)
resized_image.format = image.format # original image extension

Read the docs

documentation 中所述:

The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None.

您可以指定保存格式:

image.save(fp, 'JPEG')

您可以使用保存评论保存调整大小的图片

resized_image.save("New_image.png")

它将保存到您的当前目录。

如果你想在 python 控制台中看到你必须 运行

resized_image.show()