thumbnail image from original on the fly without using a model field?

7 views
Skip to first unread message

MikeKJ

unread,
Nov 26, 2012, 10:28:51 AM11/26/12
to django...@googlegroups.com
Trying to port up from old django this class/function and having a bit of trouble with the im.save which returns

Exception Type: IOError
Exception Value:
[Errno 2] No such file or directory 
where the no file or directroy string is a correct path from MEDIA ROOT concatenated with tiny/filename.jpg

code extract

def makeTinyThumbnail(self):
    sphot = str(self.photo)
    tinythumb = sphot.replace('\\','/').split('/')
    tinythumb[-1] = 'tiny/'+tinythumb[-1]
    tinythumb = '/'.join(tinythumb)

    if not os.path.exists(MEDIA_ROOT+tinythumb):
        im = Image.open(self.photo)
        src_width, src_height = im.size
        src_ratio = float(src_width) / float(src_height)
        dst_width, dst_height = 100, 100
        dst_ratio = float(dst_width) / float(dst_height)

        if dst_ratio < src_ratio:
            crop_height = src_height
            crop_width = crop_height * dst_ratio
            x_offset = float(src_width - crop_width) / 2
            y_offset = 0
        else:
            crop_width = src_width
            crop_height = crop_width / dst_ratio
            x_offset = 0
            y_offset = float(src_height - crop_height) / 3
        im = im.crop((int(x_offset), int(y_offset), int(x_offset)+int(crop_width), int(y_offset)+int(crop_height)))
        im.thumbnail(TINY_SIZE,Image.ANTIALIAS)
        im.save(MEDIA_ROOT+tinythumb, 'JPEG')

class Picture(models.Model):
    """
    Lots of pictures will fill up a gallery
    """
    gallery = models.ForeignKey(Gallery)
    photo = models.ImageField(upload_to='gallerys')
    priority = models.IntegerField(default=50)
    #caption = models.CharField(maxlength=255)


    def get_absolute_url(self):
        return settings.MEDIA_URL+self.photo

    def save(self):
        makeTinyThumbnail(self)
        return super(Picture, self).save()

Reply all
Reply to author
Forward
0 new messages