在 Django 中更改图像类型

Changing image type in Django

我在 Django 中有一个 ImageFieldFile 类型的图像。如果我这样做 print type(image),我会得到 <class 'django.db.models.fields.files.ImageFieldFile'>

接下来,我使用 PIL 的 Image.open(image) 打开它,通过 image.resize((20,20)) 调整大小并关闭它 image.close()

关闭后,我注意到图像的 type 已更改为 <class 'PIL.Image.Image'>

如何将其改回 <class 'django.db.models.fields.files.ImageFieldFile'>?我认为 .close() 就足够了。

我解决这个问题的方法是将它保存到一个 BytesIO 对象中,然后将其填充到一个 InMemoryUploadedFile 中。所以像这样:

from io import BytesIO
from PIL import Image
from django.core.files.uploadedfile import InMemoryUploadedFile

# Where image is your ImageFieldFile
pil_image = Image.open(image)
pil_image.resize((20, 20))

image_bytes = BytesIO()
pil_image.save(image_bytes)

new_image = InMemoryUploadedFile(
    image_bytes, None, image.name, image.type, None, None, None
)
image_bytes.close()

不是很优雅,但它完成了工作。这是在 Python 3 中完成的。不确定 Python 2 兼容性。

编辑:

实际上,事后看来,I like this answer better。希望它在我试图解决这个问题时存在。 :-\

希望这对您有所帮助。干杯!