【问题标题】:Changing image type in Django在 Django 中更改图像类型
【发布时间】:2016-06-09 23:26:06
【问题描述】:

我在 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() 就足够了。

【问题讨论】:

标签: python django image python-imaging-library


【解决方案1】:

我解决这个问题的方法是将其保存到 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。当我试图解决这个问题时希望它存在。 :-\

希望这会有所帮助。干杯!

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2015-05-03
    • 2023-04-09
    相关资源
    最近更新 更多