使用 PIL 调整大小时丢失图像格式

Losing image format when resizing with PIL

from PIL import Image

myImg = request.FILES['docfile']
myImg = Image.open(myImg)
print(myImg.format, myImg.size, myImg.mode)
myImg = myImg.resize((50, 50))
print(myImg.format, myImg.size, myImg.mode)

这里是 (django/ python 3.5) 代码的精简版。目标是调整图像大小(我不想为此使用缩略图),但将其保存在内存中,而不是将其保存到磁盘(还),因为我必须将其传回数组。

无论如何,这是 2 次打印的结果:

PNG (1300, 1300) RGBA
None (50, 50) RGBA

如您所见,调整大小后格式丢失了。我怎样才能保存它?

我记得 FILES 集合中的项目就像流一样,即一旦阅读,您必须再次将位置设置为开头。例如,您可以将内容加载到 StringIO 对象,然后从中创建图像,然后对其调用 seek(0) 并再次从该对象创建缩略图。

作为文档 says:

PIL.Image.format

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 的格式是什么是没有意义的。询问包含图像的 file 的格式是什么是有意义的。所以图像没有格式,直到你将它写入文件(或为此目的编码成某种格式)。

要保留格式,您可以这样做:

myImg = Image.open(myImg)
myImg2 = myImg.resize((50, 50))
myImg2.format = myImg.format