如何去django图像字段到PIL图像并返回? [英] how to go form django image field to PIL image and back?
问题描述
给定一个django图像字段,如何创建PIL图像,反之亦然?
简单的问题,但很难到google:(
(我将使用django-imagekit的处理器旋转已存储为模型属性的图像。)
编辑
在[41]中:m.image_1 .__ class__
输出[41]: django.db.models.fields.files.ImageFieldFile
在[42]中:f = StringIO(m.image_1.read())
在[43]中:图像.open(f)
----------------------------------------- ----------------------------------
IOError追溯(最近的最后一次呼叫)
< module>()中的ipython-input-43-39949b3b74b3>
----> 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引发IOError(无法识别图像文件)
2026
2027 #
IOError:无法识别图像文件
在[44]中:
第一个问题:
import Image
pil_image_obj = Image.open(model_instance.image_field)
第二个问题:来自django.core.files.base的cStringIO的String $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ b $ ()
try:
pil_image_obj.save(f,format ='png')
s = f.getvalue()
model_instance.image_field.save(model_instance.image_field.name,
ContentFile())
#model_instance.save()
finally:
f.close()
更新
根据OP的评论,替换 import Image
与PIL导入图片中的解决了他的问题。
Given a django image field, how do I create a PIL image and vice-versa?
Simple question, but hard to google :(
(I'm going to use django-imagekit 's processor to rotate an image already stored as model attribute.)
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]:
The first question:
import Image
pil_image_obj = Image.open(model_instance.image_field)
The second question:
from cStringIO import StringIO
from django.core.files.base import ContentFile
f = StringIO()
try:
pil_image_obj.save(f, format='png')
s = f.getvalue()
model_instance.image_field.save(model_instance.image_field.name,
ContentFile(s))
#model_instance.save()
finally:
f.close()
UPDATE
According to OP's comment, replacing import Image
with from PIL import Image
solved his problem.
这篇关于如何去django图像字段到PIL图像并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!