Help, question about upload image

31 views
Skip to first unread message

Weikang Meng

unread,
Sep 5, 2014, 3:39:42 AM9/5/14
to django...@googlegroups.com
Hello, I'm working on a Django project that need to upload images and there's limit on the image file size(like 5M). I need to compress the image if it is larger than the upper limit.
 And my problem is how can i return the compressed image data just like the format of file.read()?
Here's how I did: 
(1) get the image as a file object from the Django request.FILE
(2) get file_data, which is to return, from file.read(). and compare the length of data.
(3) Compress the image, using library Image, thumbnail function.
(4) Here comes my problem, How can return the compressed data with the format like file.read

import Image
def upload(request):
   
"""
         return: file_data  <-  file.read()
    """

    file
= request.FILE['file'] #get the image as file object
    file_data
= file.read()      #read the file
    file_size
= len(file_data) #get the file size of the image
   
if cmp(file_size, MAX_SIZE):
        im
= Image.open(file)
        im
.thumbnail((128, 128), Image.ANTIALIAS)
        file_data = ???? #Help how can i return the same format like file.read() which didn't come into the 'if' part.
   
return file_data


        

Collin Anderson

unread,
Sep 5, 2014, 2:07:44 PM9/5/14
to django...@googlegroups.com
That's more a of a pillow question than a django question, but something like this might work:

import tempfile

imagefile
= tempfile.TemporaryFile()
im
.save(imagefile)
return imagefile

孟维康

unread,
Sep 5, 2014, 3:17:51 PM9/5/14
to django...@googlegroups.com
Thanks a lot for your help.
I got another way to do that with StringIO the same way as the tempfile. Could you tell me which is better? I'm not good at programing and working on it.
http://stackoverflow.com/questions/3723220/how-do-you-convert-a-pil-image-to-a-django-file
--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/8uKRzCl2X4w/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3633e360-ff53-49e4-8da7-20acc6f4c750%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages