The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a Python script to watermark images

Here’s a Python script that adds a watermark to images using the Pillow library. This script works for PNG, JPEG, and other common formats:

python
from PIL import Image, ImageDraw, ImageFont import os def add_watermark(input_image_path, output_image_path, watermark_text, position='bottom_right', opacity=128): base = Image.open(input_image_path).convert("RGBA") # Make a blank image for the watermark with an alpha layer (RGBA) watermark_layer = Image.new("RGBA", base.size, (255, 255, 255, 0)) width, height = base.size # Choose a font and size font_size = int(min(width, height) / 20) font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" # Update this path based on your system font = ImageFont.truetype(font_path, font_size) # Initialize ImageDraw draw = ImageDraw.Draw(watermark_layer) # Get text size text_width, text_height = draw.textsize(watermark_text, font) # Calculate X, Y position margin = 10 if position == 'bottom_right': x = width - text_width - margin y = height - text_height - margin elif position == 'bottom_left': x = margin y = height - text_height - margin elif position == 'top_right': x = width - text_width - margin y = margin elif position == 'top_left': x = margin y = margin else: x = (width - text_width) // 2 y = (height - text_height) // 2 # Draw text with opacity draw.text((x, y), watermark_text, fill=(255, 255, 255, opacity), font=font) # Combine original with watermark combined = Image.alpha_composite(base, watermark_layer) # Convert back to RGB and save combined = combined.convert("RGB") combined.save(output_image_path) # Example usage if __name__ == "__main__": input_img = "input.jpg" output_img = "watermarked_output.jpg" watermark = "© YourBrand" add_watermark(input_img, output_img, watermark)

Notes:

  • Font path must be updated depending on your OS. For Windows, you might use a font path like: C:\Windows\Fonts\arial.ttf.

  • Adjust opacity, font size, and position as needed.

  • Supports batch processing with minor modifications.

Let me know if you want a batch version to watermark multiple images in a folder.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About