Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to go form django image field to PIL image and back?

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]:
like image 736
eugene Avatar asked Feb 26 '14 08:02

eugene


People also ask

How do I import an image into Python PIL?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).

Does Django require pillow?

Using PIL/Pillow is only required if you want to do image processing.

How do I display PIL images?

Try setting the image format attribute explicitly to . png (i.e. im. format = "PNG" ) before the im. show() call.


2 Answers

To go from PIL image to Django ImageField, I used falsetru's answer, but I had to update it for Python 3.

First, StringIO has been replaced by io as per: StringIO in python3

Second, When I tried io.StringIO(), I recieved an error saying: "*** TypeError: string argument expected, got 'bytes'". So I changed it to io.BytesIO() and it all worked.

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()
like image 183
FeFiFoFu Avatar answered Oct 01 '22 21:10

FeFiFoFu


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.

like image 36
falsetru Avatar answered Oct 01 '22 23:10

falsetru