1. Understand the Goal: The user wants a Python program to resize and add watermarks to images using the Pillow (PIL) library.
-
Identify Key Requirements:
- Language: Python.
- Library: Pillow (
PIL).
- Functions: Resize, Watermark.
- Input/Output: Need to handle image files (open, process, save).
-
Determine Necessary Pillow Modules:
Image: For opening, creating, resizing, and pasting images.
ImageDraw: (Optional but good) If drawing a text watermark directly.
ImageFont: (Optional but good) For customizing the text watermark font.
ImageEnhance: (Optional but good) To control watermark opacity/transparency.
-
Step-by-Step Implementation Plan:
- Step 1: Setup: Import the library.
- Step 2: The
resize function:
- Open the image.
- Use
thumbnail() or resize(). thumbnail preserves aspect ratio easily, resize gives more control but requires calculating dimensions. Let's use thumbnail for simplicity or resize with a specific width/height logic. A max-dimension approach is best for general resizing.
- Step 3: The
watermark function:
- Two main approaches for watermarks:
- Text Watermark: Draw text on the image.
- Image Watermark: Paste a transparent PNG (logo) onto the image.
- Decision: I should probably provide code for both, or a robust text watermark approach as it's most common for "Hello World" type examples. Let's do a text watermark with adjustable opacity, as that's more impressive/realistic.
- Text Watermark Logic:
- Create a transparent layer the same size as the image.
- Draw text on that layer.
- Adjust opacity of the layer.
- Composite the layer over the original image.
- Step 4: Main Execution Block: Create a dummy scenario or a function that takes file paths.
-
Drafting the Code (Mental or Scratchpad):
- Imports:
from PIL import Image, ImageDraw, ImageFont, ImageEnhance
- Resizing:
img = Image.open('input.jpg')
img.thumbnail((800, 800)) # Simple resize
- Watermarking (Text):
# Need a font. Default is tiny. Let's load default or try to load a system font.
# To handle transparency properly:
# 1. Convert base image to RGBA.
# 2. Make a blank RGBA image.
# 3. Draw text on blank image.
# 4. Combine them using alpha composite.
- Refining Watermark Logic (Opacity):
Actually,
Image.alpha_composite is the way to go, or Image.paste with a mask if it's an image logo. For text with opacity:
- Create
txt_layer.
- Draw text.
txt_layer.putalpha? No, that affects the whole image.
- Better way: Draw text on a separate layer, then apply that layer.
-
Refining the Code Structure:
I will create a clean, object-oriented or functional script. A function watermark_image that takes input_path, output_path, text, and size seems best.
-
Handling the "Resize" part: Usually, people want to resize to a specific width while maintaining aspect ratio. I'll implement that.
-
Handling the "Watermark" part: I will implement a text watermark that is centered and semi-transparent.
-
Writing the actual Python Code (Iterative Refinement):
-
Check: Does the user have a font file? I can't guarantee it.
-
Solution: Use ImageFont.load_default() but acknowledge it's small, or try/except to load a common system font (like Arial). Let's stick to load_default() to ensure the code runs everywhere without crashing due to missing font files, but mention how to change it.
-
Watermark Opacity: Pillow changed how it handles alpha over time. The standard robust way:
- Base image converted to 'RGBA'.
- Create a transparent layer:
Image.new('RGBA', img.size, (255,255,255,0)).
- Draw on it.
- Combine:
Image.alpha_composite(img, watermark_layer).
-
Constructing the Explanation:
- Start with prerequisites (
pip install Pillow).
- Provide the complete code.
- Explain specific sections (Resizing, Watermarking logic).
- Add a bonus section for Image Watermarks (Logos) since that's a common requirement too.
-
Final Code Review:
- Did I handle
IOError? Basic exception handling is good.
- Is the aspect ratio preserved during resize? Yes, use
thumbnail or calculate ratio. thumbnail is easiest.
- Is the watermark visible? Yes, set a color.
-
Output Generation: (Proceed to generate the response based on these steps).
-
Self-Correction during drafting: thumbnail modifies the image in place. resize returns a new image. If I want to chain operations (resize then watermark), resize is often better for keeping the original object reference clear, but thumbnail is great for "make it fit in this box". I will use thumbnail for resizing as it's safer for memory and easier API.
-
Watermark position: Center is standard. Calculations: (width - text_width) / 2.
-
Let's provide two examples: one simple script, one reusable function. I'll go with one robust script that defines functions and uses them.
(Self-Correction on Font): load_default() produces very small text. I should advise the user to provide a .ttf path for better results, but provide a fallback.
-
Final Polish: Add comments to the code. Ensure variable names are descriptive.
(Self-Correction regarding Image Watermark vs Text Watermark): The prompt asks for "watermark". Usually, this implies text, but sometimes a logo. I will implement Text Watermark as the primary answer (as it requires drawing logic), and add a small snippet or comment about Image (Logo) Watermarks for completeness.
Let's write the text watermark code.
- Open image.
- Resize.
- Create drawing context? No, better to create a separate transparent layer for opacity control.
- Draw text on layer.
Image.alpha_composite is cleaner than paste for this.
Let's write the resize code.
image.thumbnail((max_width, max_height)) is the Pythonic way to constrain size while keeping ratio.
Okay, ready to output.
Here is a complete Python program that uses the Pillow (PIL) library to resize images and apply a semi-transparent text watermark.
Prerequisites
First, you need to install the Pillow library if you haven't already:
pip install Pillow
The Python Program
This script defines two reusable functions: resize_image and add_watermark. It includes logic to preserve the aspect ratio during resizing and handle transparency for the watermark.
import os
from PIL import Image, ImageDraw, ImageFont
def resize_image(input_path, output_path, max_size):
"""
Resizes an image while maintaining aspect ratio.
:param input_path: Path to the original image.
:param output_path: Path to save the resized image.
:param max_size: Tuple of (width, height) representing the maximum dimensions.
"""
try:
with Image.open(input_path) as img:
# Calculate the aspect ratio
img.thumbnail(max_size)
# Save the resized image
# We handle RGBA (transparency) by saving as PNG, otherwise default to JPEG
if img.mode == "RGBA":
ext = ".png"
file_path = os.path.splitext(output_path)[0] + ext
img.save(file_path, "PNG")
else:
# Convert to RGB to avoid errors with JPEG saving if input is P/RGBA
img = img.convert("RGB")
img.save(output_path, "JPEG")
print(f"Resized image saved to: {output_path}")
except Exception as e:
print(f"Error resizing image: {e}")
def add_watermark(input_path, output_path, text, transparency=128):
"""
Adds a text watermark to an image.
:param input_path: Path to the image.
:param output_path: Path to save the watermarked image.
:param text: Watermark text string.
:param transparency: Alpha value (0 is fully transparent, 255 is opaque).
"""
try:
with Image.open(input_path).convert("RGBA") as img:
# Make a blank image for the watermark, initialized to transparent
txt_layer = Image.new('RGBA', img.size, (255, 255, 255, 0))
# Initialize drawing context
d = ImageDraw.Draw(txt_layer)
# Load a font
# You can replace "arial.ttf" with a specific font path (e.g., "Roboto-Bold.ttf")
# If the font file isn't found, it defaults to a very basic pixel font.
try:
font = ImageFont.truetype("arial.ttf", 36)
except IOError:
print("Custom font not found, using default.")
font = ImageFont.load_default()
# Calculate text size and position (Bottom Right corner with padding)
# textbbox returns (left, top, right, bottom)
bbox = d.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
padding = 20
x = img.width - text_width - padding
y = img.height - text_height - padding
# Draw the text with the specified transparency (Alpha channel)
# Color is black (0,0,0) with alpha defined by 'transparency'
d.text((x, y), text, fill=(0, 0, 0, transparency), font=font)
# Combine original image with watermark layer
watermarked = Image.alpha_composite(img, txt_layer)
# Save result
# Note: JPEG does not support transparency. We convert to RGB before saving as JPG
# or save as PNG to keep transparency.
if output_path.lower().endswith(".jpg") or output_path.lower().endswith(".jpeg"):
watermarked = watermarked.convert("RGB")
watermarked.save(output_path, "JPEG")
else:
watermarked.save(output_path, "PNG")
print(f"Watermark added. Saved to: {output_path}")
except Exception as e:
print(f"Error adding watermark: {e}")
# --- Main Execution Block ---
if __name__ == "__main__":
# Setup dummy variables for demonstration
input_file = "example.jpg"
# Create a dummy image if it doesn't exist (for testing purposes)
if not os.path.exists(input_file):
print("Creating a dummy image for testing...")
dummy_img = Image.new('RGB', (800, 600), color = 'skyblue')
dummy_img.save(input_file)
# 1. Resize the image
resized_file = "resized_example.jpg"
# Resize to max 400x400 (keeps aspect ratio)
resize_image(input_file, resized_file, (400, 400))
# 2. Add Watermark
final_file = "watermarked_example.png"
add_watermark(resized_file, final_file, text="© MyBrand", transparency=100)
Explanation of the Code
-
resize_image:
img.thumbnail(max_size): This is the most efficient way to resize in Pillow. It modifies the image in-place to fit within the tuple provided (Width, Height) while maintaining the original aspect ratio.
- Modes: We check
img.mode. If the image has transparency (RGBA), we save it as a PNG. Otherwise, we convert it to RGB to ensure it saves correctly as a JPEG.
-
add_watermark:
convert("RGBA"): We ensure the source image has an Alpha channel (transparency), even if the original JPG didn't.
Image.new('RGBA', ...): We create a separate, transparent layer the same size as the image to draw the text on. This prevents us from drawing directly onto the pixels of the photo.
ImageFont.truetype: This attempts to load a system font (like Arial). If you want a specific look, provide the full path to a .ttf file.
textbbox: Used to calculate the exact width and height of the text so we can position it mathematically (e.g., bottom-right corner).
Image.alpha_composite: This merges the transparent text layer on top of the original photo.
- Saving: Since JPEGs do not support transparency, we convert the final result back to RGB if the output extension is
.jpg.
How to use a custom font
If you want to use a specific font style (e.g., a bold branding font), download the .ttf file and update the line:
# Example for Windows or relative path
font = ImageFont.truetype("fonts/Roboto-Bold.ttf", 50)