problem in converting PIL image object to django file object for saving in imagefield model type

2,302 views
Skip to first unread message

ali Eblice

unread,
Sep 10, 2016, 3:49:58 AM9/10/16
to Django users
Hi everybody
I wanted to save PIL image object in model ImageField , but before doing that i have to convert PIL image object to django file-like object
I found a solution with stringIO but the problem is that in this solution "
io_object.len" is used and "len" is not available in pythin3
here is the link to solution:
http://stackoverflow.com/questions/3723220/how-do-you-convert-a-pil-image-to-a-django-file

So how can i convert PIL image object to
django file-like object for saving in model type ImageField
best regard

ludovic coues

unread,
Sep 10, 2016, 9:34:18 AM9/10/16
to django...@googlegroups.com
Using seek should do the trick.
It's a function, taking an offset as its first value and a flag as
second value indicating from where to apply the offset. It return the
position after the seek operation. So io_object.seek(0, os.SEEK_END)
will tell you the number of characters in io_object. That should be
equal to the size.
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/a4685c6c-f136-4d5f-8230-edb08fb30c36%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--

Cordialement, Coues Ludovic
+336 148 743 42

ali Eblice

unread,
Sep 10, 2016, 1:16:17 PM9/10/16
to Django users
Thanks for answering
problem solved by seeking

here is how i didi it in case of any one needed it:
        img = Image.open('test.png')  #first we open an image with PIL or maybe you have it from uploaded file already(you should import PIL and Image)
        img_io = io.BytesIO()            #creat in memory object by io (you should import io)
        img.save(img_io,format='png') #save your PIL image object to memory object you created by io
        #you should import InMemoryUploadedFile
        thumb = InMemoryUploadedFile(img2_io, None, 'foo2.jpeg', 'image/jpeg',thumb_io.seek(0,os.SEEK_END), None) #give your file to InMemoryUploadedFile to create django imagefield object
        #take look at this link to find out to import what things:
        https://groups.google.com/d/msgid/django-users/a4685c6c-f136-4d5f-8230-edb08fb30c36%40googlegroups.com
Reply all
Reply to author
Forward
0 new messages