Generating two thumbnails from the same image in Django
Posted
by Titus
on Stack Overflow
See other posts from Stack Overflow
or by Titus
Published on 2010-03-15T02:10:29Z
Indexed on
2010/03/15
2:39 UTC
Read the original article
Hit count: 294
Hello, this seems like quite an easy problem but I can't figure out what is going on here. Basically, what I'd like to do is create two different thumbnails from one image on a Django model. What ends up happening is that it seems to be looping and recreating the same image (while appending an underscore to it each time) until it throws up an error that the filename is to big. So, you end up something like:
OSError: [Errno 36] File name too long: 'someimg________________etc.jpg'
Here is the code:
def save(self, *args, **kwargs):
if self.image:
iname = os.path.split(self.image.name)[-1]
fname, ext = os.path.splitext(iname)
tlname, tsname = fname + '_thumb_l' + ext, fname + '_thumb_s' + ext
self.thumb_large.save(tlname, make_thumb(self.image, size=(250,250)))
self.thumb_small.save(tsname, make_thumb(self.image, size=(100,100)))
super(Artist, self).save(*args, **kwargs)
def make_thumb(infile, size=(100,100)):
infile.seek(0)
image = Image.open(infile)
if image.mode not in ('L', 'RGB'):
image.convert('RGB')
image.thumbnail(size, Image.ANTIALIAS)
temp = StringIO()
image.save(temp, 'png')
return ContentFile(temp.getvalue())
I didn't show imports for the sake of brevity. Assume there are two ImageFields on the Artist model: thumb_large, and thumb_small.
If this isn't the correct way to do it, I'd appreciate any feedback. Thanks!
© Stack Overflow or respective owner