Automating Image Watermarking with Python and Pillow
This article introduces the importance of image watermarking for copyright protection and provides a step‑by‑step Python tutorial using the Pillow library, covering installation, basic usage, a script for batch watermarking, and advanced techniques such as dynamic watermarks and automated folder monitoring.
In the digital age, images are ubiquitous, and protecting their copyright is challenging; watermarks offer an effective solution, and automating their application with Python simplifies the process.
Fundamental Knowledge: Getting Started with Pillow
Pillow is a popular Python imaging library, a friendly fork of PIL, providing powerful image processing capabilities. Install it via:
pip install PillowPractical Exercise: Batch Adding Watermarks
When handling many images, manual watermarking is inefficient. The following Python script demonstrates how to add a text watermark to an image and process a batch of files.
from PIL import Image, ImageDraw, ImageFont
def add_watermark(image_path, watermark_text, output_path):
base = Image.open(image_path).convert("RGBA")
txt = Image.new("RGBA", base.size, (255,255,255,0))
fnt = ImageFont.truetype("arial.ttf", 30)
d = ImageDraw.Draw(txt)
# calculate position
textwidth, textheight = d.textsize(watermark_text, font=fnt)
x = (base.width - textwidth) / 2
y = (base.height - textheight) / 2
# add watermark
d.text((x, y), watermark_text, font=fnt, fill=(255,255,255,128))
out = Image.alpha_composite(base, txt)
out.convert("RGB").save(output_path)
# batch processing
for i in range(1, 11): # process images 1 to 10
image_path = f"images/image_{i}.jpg"
output_path = f"watermarked/watermarked_{i}.jpg"
add_watermark(image_path, "Your Copyright ©", output_path)Advanced Tips: Dynamic Watermarks and Automation
Dynamic watermarks adjust position, size, and opacity based on image features, often using image analysis or machine‑learning models to predict optimal placement. Automated watermarking can monitor a folder and apply watermarks to new images as they appear.
import os
import time
def auto_watermark(images_dir, watermark_path, output_dir):
while True:
for filename in os.listdir(images_dir):
if filename.endswith('.jpg') and not os.path.exists(os.path.join(output_dir, filename)):
add_image_watermark(os.path.join(images_dir, filename), watermark_path, os.path.join(output_dir, filename))
time.sleep(60) # check every minute
auto_watermark('incoming_images', 'logo.png', 'watermarked_images')Subscribe to the author's WeChat channel for more content, and practice the techniques to strengthen your image copyright protection skills.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.