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 (the save method is on the Artist model):
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.
The way I am testing if this works is, in the shell:
artist = Artist.objects.get(id=1)
artist.save()
#error here after a little wait (until I assume it generates enough images that the OSError gets raised)
If this isn't the correct way to do it, I'd appreciate any feedback. Thanks!