Skip to content

Instantly share code, notes, and snippets.

@anishmenon
Last active August 29, 2015 14:02
Show Gist options
  • Save anishmenon/6a67654846dcaab736e8 to your computer and use it in GitHub Desktop.
Save anishmenon/6a67654846dcaab736e8 to your computer and use it in GitHub Desktop.
Watermark Image - PIL django python
from PIL import Image
#your views
slider = YourImageModel.objects.get(id=id)
watermark = Image.open("path to your watermark image file")
img = Image.open(slider.image.file)
img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]-watermark.size[1]),watermark)
image = img.resize((1400, 560), Image.ANTIALIAS)
image.save('{0}/{1}'.format(settings.MEDIA_ROOT,slider.image.name), quality=80)
slider.save()
@anishmenon
Copy link
Author

class Photo(models.Model):
    name = models.CharField(max_length = 100)
    photo = models.ImageField(upload_to = 'photos', blank=False,null=True)
    approved = models.BooleanField(default = False)
    uploaded_time = models.DateTimeField()
    description = models.CharField(max_length = 80 , blank = False , null = True)
    approved_by = models.CharField(max_length = 100)
    user = models.ForeignKey(User)
    total_download = models.IntegerField(default=0)
    is_watermarked = models.BooleanField(default=False)


#i've added anthr field called is_watermarked . after save do a perodic task .like

photos = Photo.objects.filter(is_watermarked=False)
watermark = Image.open("path to your watermark image file")

for photo in photos:
     img = Image.open(photo.image.file)
     img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]-watermark.size[1]),watermark)
     image = img.resize((1400, 560), Image.ANTIALIAS)
     image.save('{0}/{1}'.format(settings.MEDIA_ROOT,photo.image.name), quality=80)
     photo.is_watermarked = True
     photo.save()

@anishmenon
Copy link
Author

""" add another field original_image to your Photo model class and Create another model """
class TempFile(models.Model):
     photo = models.ImageField(upload_to = 'photos', blank=False,null=True)
     expiry = models.DateTimeField()



from django.views.static import serve
from django.core.files.base import ContentFile

# After user purchases an image
photo = Photo.objects.get(id=purchasedid).original_image
temp = TempFile(expiry=yourdatetime) 
temp.photo = Upload from 'photo' using SimpleUploadedFile
return serve(request, os.path.basename(temp.photo), os.path.dirname(temp.photo))

@Raihanveer
Copy link

How to set watermark in position of 10 pixel from bottom,because after using your code,the watermark logo showing at the bottom of the image,i want to set it in the center,is it possible?

@anishmenon
Copy link
Author

Its like a one men show .. Sorry to answer .. Please b happy with my replies and google it.

@Raihanveer
Copy link

The way you help me,it was awesome.Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment