Python Pillow creates watermarks
Creating Watermarks with Python Pillow
You’ve probably noticed that some photos online are watermarked. Watermarks are undoubtedly one of the best ways to protect your images from being misused. It’s also recommended to add watermarks to your creative photos before sharing them on social media to prevent them from being misused.
A watermark generally refers to some text or logo overlaid on a photo to identify who took the photo or who owns the rights to it.
The Pillow package allows us to add watermarks to your images. To add watermarks to images, we need the Pillow package’s Image, ImageDraw, and ImageFont modules.
The ImageDraw module adds the ability to draw 2D graphics on new or existing images. The ImageFont module is used to load bitmap, TrueType, and OpenType font files.
Example
The following Python program demonstrates how to use pillow to add a watermark to an image.
#Import required Image library
from PIL import Image, ImageDraw, ImageFont
#Create an Image Object from an Image
im = Image.open('images/boy.jpg')
width, height = im.size
draw = ImageDraw.Draw(im)
text = "sample watermark"
font = ImageFont.truetype('arial.ttf', 36)
textwidth, texttheight = draw.textsize(text, font)
# calculate the x,y coordinates of the text
margin=10
x = width - textwidth - margin
y = height - textheight - margin
# draw watermark in the bottom right corner
draw.text((x, y), text, font=font)
im.show()
#Save watermarked image
im.save('images/watermark.jpg')
Output
Assume that the following is the input image boy.jpg located in the images folder.
After executing the above program, if you look in the output folder, you should see the resulting watermark.jpg file with the watermark, as shown below.