3

I have an image of ImageFieldFile type in Django. If I do print type(image), I get <class 'django.db.models.fields.files.ImageFieldFile'>

Next, I opened this using PIL's Image.open(image), resized it via image.resize((20,20)) and closed it image.close().

After closing it, I notice image's type has changed to <class 'PIL.Image.Image'>.

How do I change it back to <class 'django.db.models.fields.files.ImageFieldFile'>? I thought .close() would suffice.

Hassan Baig
  • 15,055
  • 27
  • 102
  • 205
  • Why do you need to change it back? Is there a bigger problem here? – Lorenzo Peña Feb 26 '16 at 16:38
  • Saving it on Azure storage blob, where I keep getting a type error for ``, but not for `` – Hassan Baig Feb 26 '16 at 16:39
  • This perhaps won't be much of a help, but check some ways of editing images while uploading http://stackoverflow.com/questions/15519716/django-resize-image-during-upload and http://stackoverflow.com/questions/24373341/django-image-resizing-and-convert-before-upload – Lorenzo Peña Feb 26 '16 at 16:42
  • Possible duplicate of http://stackoverflow.com/questions/22035833/how-to-go-form-django-image-field-to-pil-image-and-back – ubadub Feb 26 '16 at 18:06

1 Answers1

1

The way I got around this was to save it to a BytesIO object then stuff that into an InMemoryUploadedFile. So something like this:

from io import BytesIO
from PIL import Image
from django.core.files.uploadedfile import InMemoryUploadedFile

# Where image is your ImageFieldFile
pil_image = Image.open(image)
pil_image.resize((20, 20))

image_bytes = BytesIO()
pil_image.save(image_bytes)

new_image = InMemoryUploadedFile(
    image_bytes, None, image.name, image.type, None, None, None
)
image_bytes.close()

Not terribly graceful, but it got the job done. This was done in Python 3. Not sure of Python 2 compatibility.

EDIT:

Actually, in hindsight, I like this answer better. Wish it existed when I was trying to solve this issue. :-\

Hope this helps. Cheers!

Community
  • 1
  • 1
CaffeineFueled
  • 561
  • 2
  • 9