English 中文(简体)
Python Pillow - Creating a Watermark
  • 时间:2024-11-03

Python Pillow - Creating a Watermark


Previous Page Next Page  

You have noticed that, some of the onpne photos are watermarked. Watermark is definitely one of the better ways to protect your images from misuse. Also, it is recommended to add watermark to your creative photos, before sharing them on social media to prevent it from being misused.

Watermark is generally some text or logo overlaid on the photo that identifies who took the photo or who owns the rights to the photo.

Pillow package allows us to add watermarks to your images. For adding watermark to our image, we need “Image”, “ImageDraw” and “ImageFont” modules from pillow package.

The ‘ImageDraw’ module adds functionapty to draw 2D graphics onto new or existing images. The ‘ImageFont’ module is employed for loading bitmap, TrueType and OpenType font files.

Example

Following python program demonstrates how to add watermark to an image using python pillow −

#Import required Image pbrary
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, textheight = 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

Suppose, following is the input image boy.jpg located in the folder image.

Boy

After executing the above program, if you observe the output folder you can see the resultant watermark.jpg file with watermark on it as shown below −

Watermark Advertisements