Batch resize and watermark images using Pillow. The watermark should be a transparent PNG centered on the image using alpha composition, scaling proportionally to always be 20% of the target image width.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a comprehensive request for batch image processing using Pillow. Let me break down the requirements:
Batch resize images
Add a transparent PNG watermark
Watermark should be centered
Use alpha composition for transparency
Scale watermark to 20% of target image width
Process multiple images
I'll create a complete solution with:
A class/function to handle the operations
Error handling
Configuration options
Example usage
Progress indication
Support for multiple image formats
Let me write a comprehensive solution:
python
from PIL import Image
import os
from pathlib import Path
from typing import Tuple, List, Optional
import logging
class ImageBatchProcessor:
def __init__(self, source_dir: str, output_dir: str, watermark_path: str, target_size: Tuple[int, int], quality: int = 95):
"""
Initialize the batch image processor.
Args:
source_dir: Directory containing source images
output_dir: Directory to save processed images
watermark_path: Path to transparent PNG watermark
target_size: Target image size as (width, height)
quality: JPEG quality (1-100)
"""
self.source_dir = Path(source_dir)
self.output_dir = Path(output_dir)
self.watermark_path = Path(watermark_path)
self.target_size = target_size
self.quality = quality
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
self.logger = logging.getLogger(__name__)
# Validate inputs
self._validate_inputs()
# Load watermark
self.watermark = self._load_watermark()
def _validate_inputs(self):
"""Validate input parameters."""
if not self.source_dir.exists():
raise ValueError(f"Source directory not found: {self.source_dir}")
if not self.watermark_path.exists():
raise ValueError(f"Watermark file not found: {self.watermark_path}")
# Create output directory if it doesn't exist
self.output_dir.mkdir(parents=True, exist_ok=True)
if self.target_size[0] <= 0 or self.target_size[1] <= 0:
raise ValueError("Target size must be positive")
def _loa
d_watermark(self) -> Image.Image:
"""Load and validate watermark image."""
try:
watermark = Image.open(self.watermark_path)
if watermark.mode != 'RGBA':
self.logger.warning(f"Converting watermark from {watermark.mode} to RGBA")
watermark = watermark.convert('RGBA')
self.logger.info(f"Watermark loaded: {watermark.size}")
return watermark
except Exception as e:
raise ValueError(f"Failed to load watermark: {e}")
I need to open the watermark file and ensure it's in RGBA format for transparency support, logging the conversion if needed. Then I'll handle the image resizing by scaling it to fit within the target dimensions while preserving aspect ratio, padding with white space as required.
For the watermark scaling, I calculate its dimensions as 20% of the target image width while maintaining the original aspect ratio. When adding the watermark, I position it centrally on the image using alpha composition to blend it properly.
To handle transparency correctly, I convert the image to RGBA mode before pasting the watermark with its alpha channel, then convert back to RGB for JPEG output. The `process_image` method handles the full pipeline of resizing and watermarking individual images. [List[str]] = None) -> Tuple[int, int]:
"""
Process all images in the source directory.
Args:
extensions: List of file extensions to process (default: common image formats)
Returns:
Tuple of (successful, failed) count
"""
if extensions is None:
extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif']
# Find all image files
image_files = []
for ext in extensions:
image_files.extend(self.source_dir.glob(f'*{ext}'))
image_files.extend(self.source_dir.glob(f'*{ext.upper()}'))
if not image_files:
self.logger.warning(f"No image files found in {self.source_dir}")
I'm setting up the batch processing method to handle multiple images at once. If no extensions are specified, I'll default to common formats like jpg, png, bmp, and gif. I need to search the source directory for files matching both lowercase and uppercase versions of each extension, then check if any images were actually found before proceeding.
Once I have the list of images, I'll iterate through each one, tracking successes and failures as I process them individually. The method returns a tuple with the counts so the caller knows how many completed successfully versus how many had issues.</think>
# Batch Image Resize and Watermark with Pillow
Here's a comprehensive solution for batch processing images with watermarking:
## Complete Solution
```python
from PIL import Image
from pathlib import Path
from typing import Tuple, List, Optional
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
class ImageBatchProcessor:
"""Batch process images: resize and add watermark."""
def __init__(
self,
source_dir: str,
output_dir: str,
watermark_path: str,
target_size: Tuple[int, int],
quality: int = 95,
preserve_aspect: bool = True
):
"""
Initialize the batch processor.
Args:
source_dir: Directory containing source images
output_dir: Directory for processed images
watermark_path: Path to transparent PNG watermark
target_size: Target size as (width, height)
quality: JPEG quality 1-100
preserve_aspect: Whether to maintain aspect ratio
"""
self.source_dir = Path(source_dir)
self.output_dir = Path(output_dir)
self.watermark_path = Path(watermark_path)
self.target_size = target_size
self.quality = quality
self.preserve_aspect = preserve_aspect
self._setup_logging()
self._validate_inputs()
self.watermark = self._load_watermark()
def _setup_logging(self):
"""Configure logging."""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
self.logger = logging.getLogger(__name__)
def _validate_inputs(self):
"""Validate all input parameters."""
if not self.source_dir.exists():
raise ValueError(f"Source directory not found: {self.source_dir}")
if not self.watermark_path.exists():
raise ValueError(f"Watermark not found: {self.watermark_path}")
self.output_dir.mkdir(parents=True, exist_ok=True)
if self.target_size[0] <= 0 or self.target_size[1] <= 0:
raise ValueError("Target size must be positive integers")
def _load_watermark(self) -> Image.Image:
"""Load watermark and convert to RGBA."""
try:
watermark = Image.open(self.watermark_path)
if watermark.mode != 'RGBA':
self.logger.info(f"Converting watermark from {watermark.mode} to RGBA")
watermark = watermark.convert('RGBA')
self.logger.info(f"Watermark loaded: {watermark.size}")
return watermark
except Exception as e:
raise RuntimeError(f"Failed to load watermark: {e}")
def _resize_image(self, image: Image.Image) -> Image.Image:
"""
Resize image to target size.
If preserve_aspect=True: pads with white; otherwise stretches.
"""
if self.preserve_aspect:
return self._resize_preserve_aspect(image)
else:
return image.resize(self.target_size, Image.Resampling.LANCZOS)
def _resize_preserve_aspect(self, image: Image.Image) -> Image.Image:
"""Resize while preserving aspect ratio, padding with white."""
# Calculate scaling factor
scale = min(
self.target_size[0] / image.width,
self.target_size[1] / image.height
)
new_size = (
int(image.width * scale),
int(image.height * scale)
)
# Resize image
resized = image.resize(new_size, Image.Resampling.LANCZOS)
# Create canvas and center the resized image
canvas = Image.new('RGB', self.target_size, 'white')
offset = (
(self.target_size[0] - resized.width) // 2,
(self.target_size[1] - resized.height) // 2
)
canvas.paste(resized, offset)
return canvas
def _scale_watermark(self, target_width: int) -> Image.Image:
"""
Scale watermark to 20% of target image width.
Maintains aspect ratio.
"""
new_width = int(target_width * 0.20)
aspect_ratio = self.watermark.height / self.watermark.width
new_height = int(new_width * aspect_ratio)
scaled = self.watermark.resize(
(new_width, new_height),
Image.Resampling.LANCZOS
)
self.logger.debug(f"Watermark scaled to: {scaled.size}")
return scaled
def _add_watermark(self, image: Image.Image) -> Image.Image:
"""
Add centered watermark using alpha composition.
"""
# Scale watermark to 20% of image width
scaled_watermark = self._scale_watermark(image.width)
# Calculate center position
x_offset = (image.width - scaled_watermark.width) // 2
y_offset = (image.height - scaled_watermark.height) // 2
# Convert to RGBA for alpha composition
if image.mode != 'RGBA':
image = image.convert('RGBA')
# Create a layer for the watermark
watermark_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
watermark_layer.paste(scaled_watermark, (x_offset, y_offset), scaled_watermark)
# Alpha composite: blend watermark with image
image = Image.alpha_composite(image, watermark_layer)
# Convert back to RGB for JPEG (if needed)
if image.mode == 'RGBA':
rgb_image = Image.new('RGB', image.size, 'white')
rgb_image.paste(image, mask=image.split()[3]) # Use alpha channel as mask
image = rgb_image
return image
def process_image(self, image_path: Path) -> Tuple[bool, str]:
"""
Process single image: resize and watermark.
Returns:
(success, message)
"""
try:
with Image.open(image_path) as image:
original_size = image.size
self.logger.info(f"Processing: {image_path.name} {original_size}")
# Convert to RGB if necessary (handles PNG, GIF, etc.)
if image.mode in ('RGBA', 'LA', 'P'):
if image.mode == 'P':
image = image.convert('RGB')
else:
# Create white background for transparency
background = Image.new('RGB', image.size, 'white')
background.paste(image, mask=image.split()[-1])
image = background
# Resize
image = self._resize_image(image)
# Add watermark
image = self._add_watermark(image)
# Save
output_path = self.output_dir / image_path.name
image.save(output_path, 'JPEG', quality=self.quality, optimize=True)
message = f"✓ {image_path.name}: {original_size} → {self.target_size}"
self.logger.info(message)
return True, message
except Exception as e:
message = f"✗ {image_path.name}: {str(e)}"
self.logger.error(message)
return False, message
def batch_process(
self,
extensions: Optional[List[str]] = None,
max_workers: int = 4
) -> dict:
"""
Process all images in source directory.
Args:
extensions: File extensions to process
max_workers: Number of parallel threads
Returns:
Statistics dictionary
"""
if extensions is None:
extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']
# Find all image files
image_files = []
for ext in extensions:
image_files.extend(self.source_dir.glob(f'*{ext}'))
image_files.extend(self.source_dir.glob(f'*{ext.upper()}'))
image_files = list(set(image_files)) # Remove duplicates
if not image_files:
self.logger.warning(f"No images found in {self.source_dir}")
return {'successful': 0, 'failed': 0, 'total': 0}
self.logger.info(f"Found {len(image_files)} images")
results = {'successful': 0, 'failed': 0, 'total': len(image_files), 'messages': []}
# Single-threaded or multi-threaded processing
if max_workers == 1:
for image_path in image_files:
success, message = self.process_image(image_path)
results['messages'].append(message)
if success:
results['successful'] += 1
else:
results['failed'] += 1
else:
# Multi-threaded processing
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(self.process_image, img): img
for img in image_files
}
for future in as_completed(futures):
success, message = future.result()
results['messages'].append(message)
if success:
results['successful'] += 1
else:
results['failed'] += 1
self.logger.info(
f"Complete: {results['successful']}/{results['total']} successful, "
f"{results['failed']} failed"
)
return results
# Standalone function for simple usage
def batch_watermark_images(
source_dir: str,
output_dir: str,
watermark_path: str,
width: int,
height: int,
quality: int = 95
) -> dict:
"""Simple wrapper function."""
processor = ImageBatchProcessor(
source_dir=source_dir,
output_dir=output_dir,
watermark_path=watermark_path,
target_size=(width, height),
quality=quality
)
return processor.batch_process(max_workers=4)
# Create processor with custom settings
processor = ImageBatchProcessor(
source_dir='./raw_images',
output_dir='./watermarked',
watermark_path='./logo.png',
target_size=(1600, 900),
quality=90,
preserve_aspect=True
)
# Process with multiple threads
results = processor.batch_process(
extensions=['.jpg', '.png'],
max_workers=8
)
# Print results
print(f"Successfully processed: {results['successful']}")
print(f"Failed: {results['failed']}")
for msg in results['messages']:
print(msg)
Create Sample Watermark
python
def create_sample_watermark(output_path: str = 'watermark.png'):
"""Create a sample transparent watermark."""
import os
# Create a simple watermark with text
watermark = Image.new('RGBA', (200, 200), (0, 0, 0, 0))
pixels = watermark.load()
# Draw a simple border
for x in range(200):
for y in range(200):
if x < 10 or x > 190 or y < 10 or y > 190:
pixels[x, y] = (0, 0, 0, 100) # Semi-transparent black
watermark.save(output_path)
print(f"Sample watermark created: {output_path}")
# Create sample
create_sample_watermark()
Features
✅ Batch processing with progress tracking
✅ Aspect ratio preservation with white padding
✅ Alpha composition for proper transparency blending
✅ Automatic watermark scaling to 20% of image width
✅ Centered watermark positioning
✅ Multi-threaded processing for speed
✅ Error handling and detailed logging
✅ Multiple image format support
✅ Quality control for output images
Performance Tips
python
# For fast processing with many images
results = processor.batch_process(max_workers=8)
# For slower machines, use single thread
results = processor.batch_process(max_workers=1)
This solution provides a robust, production-ready image batch processor with proper transparency handling and extensive logging!