gpt4 book ai didi

python - 在 Django 中更改图像类型

转载 作者:行者123 更新时间:2023-11-28 18:32:26 24 4
gpt4 key购买 nike

我有一张 ImageFieldFile 的图片输入 Django。如果我这样做 print type(image) , 我得到 <class 'django.db.models.fields.files.ImageFieldFile'>

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

关闭它后,我注意到图像的类型 已更改为<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 .希望它在我试图解决这个问题时存在。 :-\

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

关于python - 在 Django 中更改图像类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35656933/

24 4 0
文章推荐: Python - Pandas 数据框 - 生成包含组级信息的列
文章推荐: python - imgur 上的图像格式
文章推荐: css - 停止继承特定
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com