Python - Adding Watermark



Description

WatermarkOriginally a watermark is a more or less transparent image or text that has been applied to a piece of paper, another image to either protect the original image, or to make it harder to copy the item e.g. money watermarks or stamp watermarks

Python with Image Library supports capturing the screenshot to any kind of image format.

For saving the image to pdf we need to import Image,ImageGrab and time module .

Image module :Image is the fundamental module for loading and opening the image and ImageGrab module is useful for taking the screenshot of the screen.
ImageDraw module :ImageDraw helps with Drawing interface options
ImageFont module :ImageFont provides all the methods for integrating the font with the program

Example

The following example shows how to create watermark images on the image.

from PIL import Image, ImageDraw, ImageFont, ImageEnhance
import os, sys
FONT = 'arialbi.ttf'
in_file="watermark_original.png"
text = "Giridhar"
out_file='after_watermark.jpg'
angle=23
opacity=0.25
img = Image.open(in_file).convert('RGB')
watermark = Image.new('RGBA', img.size, (0,0,0,0))
size = 4
n_font = ImageFont.truetype(FONT, size)
n_width, n_height = n_font.getsize(text)

while n_width+n_height size += 2
n_font = ImageFont.truetype(FONT, size)
n_width, n_height = n_font.getsize(text)

draw = ImageDraw.Draw(watermark, 'RGBA')
draw.text(((watermark.size[0] - n_width) / 2,(watermark.size[1] - n_height) / 2),text, font=n_font)
watermark = watermark.rotate(angle,Image.BICUBIC)
alpha = watermark.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
watermark.putalpha(alpha)
Image.composite(watermark, img, watermark).save(out_file, 'JPEG')
Image.composite(watermark, img, watermark).show(out_file, 'JPEG')


Advertisements