2014-02-26 124 views
12

給定一個django圖像字段,我該如何創建一個PIL圖像,反之亦然?如何將django圖像場形成爲PIL圖像並返回?

簡單的問題,但很難谷歌:(

(我將使用Django的imagekit的處理器旋轉已存儲的模型屬性。圖像)

編輯

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]: 
+0

難道這不是'導入圖像; pil_image = Image.open(my_image_from_image_field.name)'工作? – Bernhard

+0

@Bernhard,'.name'是相對於'MEDIA_ROOT'。它可以被省略,因爲ImageField/FileField像文件對象一樣操作。 – falsetru

回答

13

的第一個問題:

import Image 

pil_image_obj = Image.open(model_instance.image_field) 

第二個問題:

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

根據OP的評論,與from PIL import Image更換import Image解決他的問題。

+0

(Pdb)p Image.open(obj.image_1) p Image.open(obj.image_1) *** IOError:IOError('can not identify image file',)for#1 .. – eugene

+0

@eugene,How關於'pil_image_obj = Image.open(model_instance.image_field.path)'? – falsetru

+0

它說,沒有實現路徑,因爲後端因爲(s3boto)不支持絕對路徑 – eugene

18

從PIL圖像去的Django ImageField的,我用falsetru的答案,但我不得不更新爲Python 3

首先,StringIO的已取代IO按: 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()