Python Pillow - Creating a Watermark

Python Pillow - Creating a Watermark

Using the Python Imaging Library (Pillow), you can easily create and add watermarks to images. Here's a step-by-step guide on how to do it:

1. Install Pillow

If you haven't installed Pillow yet:

pip install pillow

2. Watermarking an Image

Here's a script that demonstrates how to add a text watermark to an image:

from PIL import Image, ImageDraw, ImageFont

def add_watermark(input_image_path, output_image_path, watermark_text):
    # Open the original image
    original_image = Image.open(input_image_path)
    width, height = original_image.size

    # Create a drawing context
    transparent = Image.new('RGBA', original_image.size, (255, 255, 255, 0))
    drawing = ImageDraw.Draw(transparent)

    # Load a font
    font = ImageFont.truetype('arial.ttf', 30)  # Choose your font and size

    # Position the watermark at the bottom right corner, with 10px margin
    text_width, text_height = drawing.textsize(watermark_text, font)
    x = width - text_width - 10
    y = height - text_height - 10

    # Add watermark text to the transparent image
    drawing.text((x, y), watermark_text, fill=(255, 255, 255, 255), font=font)

    # Blend the original image and the watermark
    watermarked_image = Image.alpha_composite(original_image.convert('RGBA'), transparent)

    # Save the result
    watermarked_image.save(output_image_path, "PNG")  # Save as PNG to retain transparency

# Example usage
add_watermark('path_to_original.jpg', 'path_with_watermark.png', 'Your Watermark Here')

Some important notes:

  • The watermark is added as semi-transparent white text at the bottom right corner.

  • The code assumes the availability of the Arial font ('arial.ttf'). If you don't have this font or are running the script on a platform where Arial isn't available, you'll need to specify the path to another TrueType font file.

  • If you want the watermark to be less transparent, you can adjust the fill parameter's fourth value (currently 255, which means fully opaque). For example, use fill=(255, 255, 255, 128) for half transparency.

This example demonstrates adding a textual watermark. If you want to use an image as a watermark, the process is a bit different, but the idea is similar: you'll overlay the watermark image on the original, adjusting its transparency as desired.


More Tags

exchangewebservices uikeyinput ansible-template jtableheader gmail tinymce chart.js2 electron-builder asp.net-3.5 azure-pipelines-release-pipeline

More Programming Guides

Other Guides

More Programming Examples