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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With