class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="person")
image = models.ImageField(upload_to='site-media/media/userimages/', default = 'site-media/user_default.jpeg')
thumbnail = models.ImageField(upload_to="site-media/media/userimages/userthumbs/", blank=True, null=True)
thumbnail2 = models.ImageField(upload_to="site-media/media/userimages/userthumbs2/", blank=True, null=True)
pub_date = models.DateTimeField(auto_now_add=True)
bio = models.CharField(max_length=300, blank = True)
def create_thumbnail(self):
if not self.image:
return
IMAGE_SIZE = (150,150)
user_name = self.user.username
image = Image.open(StringIO(self.image.read()))
imagef = ImageOps.fit(image, IMAGE_SIZE, Image.ANTIALIAS)
temp_handle = StringIO()
imagef.save(temp_handle, 'jpeg')
temp_handle.seek(0)
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type='image/jpeg')
self.image.save('%s.%s'%(user_name,'jpeg'), suf, save=False)
THUMBNAIL_SIZE = (100,100)
image = Image.open(StringIO(self.image.read()))
thumb = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS)
temp_handle = StringIO()
thumb.save(temp_handle, 'jpeg')
temp_handle.seek(0)
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type='image/jpeg')
self.thumbnail.save('%s_thumb.%s'%(user_name,'jpeg'), suf, save=False)
THUMBNAIL2_SIZE = (32,32)
thumb2 = ImageOps.fit(image, THUMBNAIL2_SIZE, Image.ANTIALIAS)
temp_handle = StringIO()
thumb2.save(temp_handle, 'jpeg')
temp_handle.seek(0)
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type='image/jpeg')
self.thumbnail2.save('%s_thumb2.%s'%(user_name,'jpeg'), suf, save=False)
def save(self, *args, **kwargs):
"""Save image dimensions."""
self.create_thumbnail()
super(UserProfile, self).save(*args, **kwargs)
This is a model for a user's profile. It woks great. The problem with this code is, whenever I update the textfields, the thumbnails and image gets created again without the previous ones being deleted. This is a certailnly a bad thing. So, is there a way to avoid copies of image and thumbnails with each update of the textfields? I thought of creating the thumbnails in the view, but, I couldn't write a working code.
Use solr-thumbnail for the job.
Simply use the ImageField
provided by the app and all your troubles will go away. :)
In your case you'll need only image
field in the model. With solr-thumbnail
all you need is one file to create many thumbnails in various sizes out of it. The app also deletes thumbnails when the original file is no more.
Installation process is a breeze as well.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments