Outlining Project Requirements
I'm currently fleshing out the necessary Python program specifications. I've pinpointed that the program should process a variable number of input images. I'm focusing on defining the precise functionalities: image resizing, and watermark integration using Pillow.
Detailing Functionalities Further
I'm now prioritizing the resizing aspects. I've decided to move towards resize with an aspect ratio constraint, to allow more precise sizing and to prevent distortion. Subsequently, I'm focusing on the watermark feature, leaning towards text-based watermarks for initial implementation, setting font, size, color and opacity. Positioning of the watermark, likely in a corner, is next on the agenda.
Formulating the Implementation Plan
Now, I'm charting the precise steps for code implementation. I'm focusing on creating distinct functions for resizing and watermarking. Resizing will use resize function, with aspect ratio preservation. For the watermark, I am leaning toward incorporating text and allowing opacity control. The main block will handle file paths and function calls.
Codifying Function Implementations
My focus has shifted to the actual code. I'm starting with the resize_image function, prioritizing aspect ratio preservation using the thumbnail method for simplicity, and aiming for a concise implementation. Next, I'm tackling the watermarking function, specifically working on text-based watermarks. I'm exploring font loading, position calculation and integrating opacity.
Constructing Code Modules
I'm presently building the Python functions. First is resize_image using the thumbnail method for image resizing, ensuring aspect ratio preservation with simplicity. I then am designing add_watermark for the text watermark, including the dynamic calculation of position and font size. I'm focusing on text-based watermarks for initial implementation, aiming for flexibility.
Developing the Core Functions
I'm presently building the essential Python functions. I'll utilize thumbnail for image resizing, ensuring aspect ratio preservation for simplicity. Regarding the watermark, I'm concentrating on text integration with calculated position and font size. I am prioritizing text-based watermarks for initial implementation, aiming to make it flexible and easy to use.
Here is a complete, robust Python script to resize images and add a transparent text watermark using the Pillow library.
Prerequisites
You will need to install the Pillow library first:
pip install Pillow
The Python Script
This script includes a function process_image that handles:
- Resizing: It uses
thumbnail to resize while maintaining the aspect ratio (so the image doesn't get stretched).
- Watermarking: It creates a transparent text overlay.
- Dynamic Font Sizing: It calculates the font size based on the image width so the watermark looks proportional regardless of image resolution.
from PIL import Image, ImageDraw, ImageFont
import os
def process_image(input_path, output_path, new_width, watermark_text):
"""
Resizes an image and adds a text watermark.
"""
try:
# Open the original image
with Image.open(input_path) as img:
# --- 1. RESIZING ---
# Calculate height to maintain aspect ratio
width_percent = (new_width / float(img.size[0]))
new_height = int((float(img.size[1]) * float(width_percent)))
# Resize using LANCZOS filter for high quality
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# --- 2. WATERMARKING ---
# Convert image to RGBA to allow transparency
base_image = img.convert("RGBA")
# Create a transparent layer for the watermark
txt_layer = Image.new("RGBA", base_image.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(txt_layer)
# -- Dynamic Font Calculation --
# We want the font height to be roughly 5% of image height
font_size = int(new_height * 0.05)
try:
# Try to load a system font (Arial usually works on Windows/macOS)
# For Linux, you might need "DejaVuSans.ttf"
font = ImageFont.truetype("arial.ttf", font_size)
except OSError:
# Fallback to default font if system font not found
print("Custom font not found, using default.")
font = ImageFont.load_default()
# Calculate text size and position (Bottom Right)
# textbbox returns (left, top, right, bottom)
bbox = draw.textbbox((0, 0), watermark_text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
margin = 20
x = base_image.width - text_width - margin
y = base_image.height - text_height - margin
# Draw the text: (R, G, B, Alpha) -> Alpha 128 is 50% opacity
watermark_color = (255, 255, 255, 128) # White semi-transparent
# Add a slight black shadow for readability on light backgrounds
shadow_color = (0, 0, 0, 128)
draw.text((x+2, y+2), watermark_text, font=font, fill=shadow_color)
draw.text((x, y), watermark_text, font=font, fill=watermark_color)
# Combine the original image with the watermark layer
combined = Image.alpha_composite(base_image, txt_layer)
# --- 3. SAVING ---
# Convert back to RGB to save as JPEG (JPEG doesn't support transparency)
final_image = combined.convert("RGB")
final_image.save(output_path, "JPEG", quality=90)
print(f"Success: Saved to {output_path}")
except Exception as e:
print(f"Error processing {input_path}: {e}")
# --- USAGE EXAMPLE ---
if __name__ == "__main__":
# Create a sample image for testing if it doesn't exist
if not os.path.exists("input.jpg"):
img = Image.new('RGB', (800, 600), color = 'blue')
img.save('input.jpg')
print("Created sample 'input.jpg'")
# Configuration
input_file = "input.jpg"
output_file = "output_resized_watermarked.jpg"
target_width = 400
text = "© My Copyright 2024"
process_image(input_file, output_file, target_width, text)
Key Features Explained
-
Image.convert("RGBA"):
- Normal JPEGs are "RGB". To have a watermark that is see-through (transparent), we must convert the image to "RGBA" (Red, Green, Blue, Alpha). The Alpha channel controls usage opacity.
-
Image.new("RGBA", ...):
- We do not draw directly on the original photo. We create a new blank, transparent "sheet" (layer), draw the text on that sheet, and then place it on top of the photo using
Image.alpha_composite.
-
textbbox:
- In older versions of Pillow,
textsize was used. In Pillow 10.0+, this was removed. This script uses textbbox, which is the modern, correct way to calculate the width and height of the text so we can position it perfectly in the corner.
-
Resampling.LANCZOS:
- When resizing images, pixels must be removed. The "Lanczos" filter provides the highest quality downsampling, ensuring the resized image remains sharp.
How to customize
- Change Position: To put the text in the center, calculate
x and y like this:
x = (base_image.width - text_width) / 2
y = (base_image.height - text_height) / 2
- Change Font: If you have a specific brand font (e.g.,
Roboto-Bold.ttf), put the .ttf file in the same folder as the script and change "arial.ttf" to your filename.
- Image Watermark (Logo): If you want to use a logo instead of text, use
paste with a mask:
logo = Image.open("logo.png").resize((50, 50))
base_image.paste(logo, (x, y), logo) # The 3rd argument acts as the transparency mask