python - Resizing uploaded files in django using PIL -


i using pil resize uploaded file using method:

def resize_uploaded_image(buf):   imagefile = stringio.stringio(buf.read())   imageimage = image.open(imagefile)    (width, height) = imageimage.size   (width, height) = scale_dimensions(width, height, longest_side=240)    resizedimage = imageimage.resize((width, height)) return resizedimage 

i use method resizedimage in main view method:

image = request.files['avatar'] resizedimage = resize_uploaded_image(image) content = django.core.files.file(resizedimage) acc = account.objects.get(account=request.user) acc.avatar.save(image.name, content) 

however, gives me 'read' error.

trace:

exception type: attributeerror @ /myapp/editavatar exception value: read

any idea how fix this? have been @ hours! thanks!

nikunj

here's how can take file-like object, manipulate image in pil, turn file-like object:

def resize_uploaded_image(buf):     image = image.open(buf)      (width, height) = image.size     (width, height) = scale_dimensions(width, height, longest_side=240)      resizedimage = image.resize((width, height))      # turn file-like object     resizedimagefile = stringio.stringio()     resizedimage.save(resizedimagefile , 'png', optimize = true)     resizedimagefile.seek(0)    # next read starts @ beginning      return resizedimagefile 

note there's handy thumbnail() method pil images. variant of thumbnail code use in own project:

def resize_uploaded_image(buf):     cstringio import stringio     import image      image = image.open(buf)      maxsize = (240, 240)     resizedimage = image.thumbnail(maxsize, image.antialias)      # turn file-like object     resizedimagefile = stringio()     resizedimage.save(resizedimagefile , 'png', optimize = true)     resizedimagefile.seek(0)    # next read starts @ beginning      return resizedimagefile 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -