Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing image type in Django

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.

like image 964
Hassan Baig Avatar asked Jun 02 '26 11:06

Hassan Baig


1 Answers

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!

like image 73
CaffeineFueled Avatar answered Jun 04 '26 00:06

CaffeineFueled