views:

1707

answers:

4

How can I easily resize an image after it has been uploaded in Django? I am using Django 1.0.2 and I've installed PIL.

I was thinking about overriding the save() method of the Model to resize it, but I don't really know how to start out and override it.

Can someone point me in the right direction? Thanks :-)

@Guðmundur H: This won't work because the django-stdimage package does not work on Windows :-(

+3  A: 

You should use a method to handle the uploaded file, as demonstrated in the Django documentation.

In this method, you could concatenate the chunks in a variable (rather than writing them to disk directly), create a PIL Image from that variable, resize the image and save it to disk.

In PIL, you should look at Image.fromstring and Image.resize.

Can Berk Güder
+2  A: 

I recommend using StdImageField from django-stdimage, it should handle all the dirty work for you. It's easy to use, you just specify the dimensions of the resized image in the field definition:

class MyModel(models.Model):
    image = StdImageField(upload_to='path/to/img',  size=(640, 480))

Check out the docs — it can do thumbnails also.

Guðmundur H
This doesn't seem to work on a Windows machine :-( It is a known bug in the django-stdimage package. There is some kind of recursion error
Windows can't recurse. It's a linux only feature :)
Codygman
works on win32 for me.
mojo
+1  A: 

I highly recommend the sorl-thumbnail app for handling image resizing easily and transparently. It goes in every single Django project I start.

Carl Meyer
A: 

I test and django-stdimage and it's really easy and fast to user. Vote for it!

Martin
This is a comment. Post is to @Guðmundur H's answer.
Török Gábor