[Django]-How to go from django image field to PIL image and back?

26👍

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.

27👍

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()

Leave a comment