2

I want to create thumbnails for uploaded images. I know there are some libraries available, but I have very basic needs and I would prefer to do this on my own.

My model goes like this:

from image_tools import resize

class Photo(models.Model):
    # some fields
    image = models.ImageField(
                upload_to='images',
                height_field='height',
                width_field='width'
            )
    thumb = models.ImageField(
        upload_to='thumbs',
        editable=False
    )

    def save(self):
        self.thumb = self.image
        resize(self.image.path, self.thumb.path, 50, 40)
        super(Photo, self).save()

Here resize() is a simple function I have written which accepts as arguments the original file path and the destination path and the dimensions and stores a thumbnail. The only problem is that the file is not yet on the disk at this moment.

Is there a way to force saving the file itself on its location, so that it will be available to my function?

Please, feel free to suggest better ways to handle this matter. Still I would like to know how to handle files which are not yet saved, whatever the best solution turns out to be.

2 Answers 2

1

There are a few ways to do this. One you have the raw image data, you can write it to a file pretty easily (look up django file uploading to see how to save an uploaded file to disk). You can read any file your django process (or apache) has access to, not just in the path of your django instance.

Another thing you can do before saving this is to use PIL to thumbnail the image and save it:
http://effbot.org/imagingbook/image.htm

You can also upload the data to s3 using boto s3, if you want the images hosted on a CDN.

1
  • I have read django file uploading, and I did not find the answer to my question. Can you be a bit more specific? "Once you have the raw image data, you can write it to a file pretty easily" is exactly the thing I am asking how to do.
    – Andrea
    May 5, 2011 at 10:40
1

Storing the file directly is not a good idea because you ignore the default file storage (i.e. file system, amazon s3, ...)

Better approach is to use django File class

from django.core.files import File
# Create a Python file object using open() and the with statement
>>> with open('/tmp/hello.world', 'w') as f:
...     myfile = File(f)
...     myfile.write('Hello World')

Also to delete the file use the default storage class See link below for more details https://docs.djangoproject.com/en/1.5/topics/files/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.