给定 django 图像字段,如何创建 PIL 图像,反之亦然?
简单的问题,但很难谷歌:(
(我将使用 django-imagekit 的处理器来旋转已存储为模型属性的图像。)
edit
In [41]: m.image_1.__class__
Out[41]: django.db.models.fields.files.ImageFieldFile
In [42]: f = StringIO(m.image_1.read())
In [43]: Image.open(f)
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-43-39949b3b74b3> in <module>()
----> 1 Image.open(f)
/home/eugenekim/virtualenvs/zibann/local/lib/python2.7/site-packages/PIL/Image.pyc in open(fp, mode)
2023 pass
2024
-> 2025 raise IOError("cannot identify image file")
2026
2027 #
IOError: cannot identify image file
In [44]:
为了从 PIL 图像转到 Django ImageField,我使用了 falsetru 的答案,但我必须将其更新为 Python 3。
首先,StringIO 已被 io 取代,如下所示:python3中的StringIO https://stackoverflow.com/questions/11914472/stringio-in-python3
第二,当我尝试时io.StringIO()
,我收到一条错误消息:"*** TypeError: string argument expected, got 'bytes'"
。所以我把它改为io.BytesIO()
这一切都奏效了。
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
f = BytesIO()
try:
pil_image_obj.save(f, format='png')
model_instance.image_field.save(model_instance.image_field.name,
ContentFile(f.getvalue()))
#model_instance.save()
finally:
f.close()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)