Sure, I'll combine the two functions resize_image and resize_images into a single, cohesive function named resize_images. This unified function will handle resizing multiple images within a specified input folder and save the resized images to an output folder. It incorporates the logic from resize_image to process each image and uses a thread pool for concurrent processing, ensuring efficiency when dealing with multiple files.
Here's the refactored code:
import subprocess
import time
from pathlib import Path
from typing import List
from concurrent.futures import ThreadPoolExecutor, as_completed
def resize_images(input_folder: Path, output_folder: Path, image_processor: 'ImageProcessor') -> None:
"""Resize all images in the input folder and save them to the output folder."""
def check_imagemagick():
"""Ensure ImageMagick is installed."""
try:
subprocess.run(
[str(Config.IMAGEMAGICK), '-version'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True
)
except subprocess.CalledProcessError:
raise FileNotFoundError("ImageMagick is not installed or not found in PATH.")
def log_error(message: str):
"""Log an error message."""
# Implement logging mechanism as needed
print(f"ERROR: {message}")
def create_temp_folder() -> Path:
"""Create and return a temporary folder path."""
temp_folder = Path("temp")
temp_folder.mkdir(exist_ok=True)
return temp_folder
def resize_single_image(input_path: Path, output_path: Path) -> Path:
"""Resize a single image using ImageMagick."""
output_path = output_path.with_suffix('.png')
identify_command = [
str(Config.IMAGEMAGICK),
str(input_path),
'-format', '%wx%h',
'info:'
]
try:
result = subprocess.run(
identify_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
current_width, current_height = map(int, result.stdout.strip().split('x'))
except subprocess.CalledProcessError as e:
log_error(f"ImageMagick identify failed for {input_path}: {e.stderr.strip()}")
return output_path
resize_mode = app.RESIZE_MODE.get()
maintain_aspect = app.maintain_aspect_ratio.get()
if resize_mode == "Fit":
target_width = int(app.RESIZE_WIDTH.get() or 0)
target_height = int(app.RESIZE_HEIGHT.get() or 0)
if maintain_aspect:
if target_width == 0 and target_height > 0:
target_width = int(target_height * current_width / current_height)
elif target_height == 0 and target_width > 0:
target_height = int(target_width * current_height / current_width)
resize_arg = f'{target_width}x{target_height}!'
else: # Shortest Side
target_size = int(app.RESIZE_SIDE.get())
resize_arg = f'{target_size}x{target_size}^'
is_upscaling = (
(resize_mode == "Fit" and (target_width > current_width or target_height > current_height)) or
(resize_mode == "Shortest Side" and target_size > min(current_width, current_height))
)
command = [
str(Config.IMAGEMAGICK),
str(input_path),
]
if is_upscaling:
command += [
'-filter', 'LanczosSharp',
'-distort', 'Resize', resize_arg,
]
else:
command += [
'-colorspace', 'RGB',
'-filter', 'Lanczos2Sharp',
'-resize', resize_arg,
'-colorspace', 'sRGB',
]
command += [
'-define', 'png:compression-level=5',
str(output_path)
]
try:
result = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
if result.stderr:
log_error(f"ImageMagick: {result.stderr.strip()}")
except subprocess.CalledProcessError as e:
log_error(f"ImageMagick resize failed for {input_path}: {e.stderr.strip()}")
return output_path
def gather_tasks(input_folder: Path) -> List[Path]:
"""Gather all image files from the input folder."""
return [
input_path for input_path in input_folder.rglob('*')
if input_path.is_file() and input_path.suffix.lower() in Config.IMAGE_EXTENSIONS
]
def process_task(input_path: Path, output_folder: Path) -> None:
"""Process a single image resizing task."""
relative_path = input_path.relative_to(input_folder)
output_path = output_folder / relative_path
output_path.parent.mkdir(parents=True, exist_ok=True)
resize_single_image(input_path, output_path)
# Start of the main function logic
try:
check_imagemagick()
except FileNotFoundError as e:
log_error(str(e))
return
tasks = gather_tasks(input_folder)
if not tasks:
log_error(f"No image files found in '{input_folder}'")
return
with create_temp_folder() as temp_folder:
start_time = time.time()
with ThreadPoolExecutor() as executor:
future_to_path = {executor.submit(process_task, path, output_folder): path for path in tasks}
for future in as_completed(future_to_path):
path = future_to_path[future]
try:
future.result()
except Exception as exc:
log_error(f"{path} generated an exception: {exc}")
elapsed_time = time.time() - start_time
print(f"Resized {len(tasks)} images in {elapsed_time:.2f} seconds.")
Explanation of Changes:
-
Unified Function: Combined both resize_image and resize_images into a single resize_images function that handles multiple image resizing tasks.
-
Helper Functions:
check_imagemagick: Verifies if ImageMagick is installed.
log_error: A placeholder for error logging. Replace the print statement with your preferred logging mechanism.
create_temp_folder: Creates a temporary folder if needed. Adjust the path as per your requirements.
resize_single_image: Encapsulates the logic from the original resize_image function to resize individual images.
gather_tasks: Collects all image files from the input directory based on allowed extensions.
process_task: Prepares the output path and calls resize_single_image for each image.
-
Concurrency: Utilized ThreadPoolExecutor from the concurrent.futures module to process multiple images concurrently, improving performance.
-
Error Handling: Enhanced error handling to catch exceptions during individual image processing without halting the entire resizing operation.
-
Performance Logging: Added a simple timing mechanism to log how long the resizing process takes. Adjust or remove as needed.
-
Path Handling: Ensured that the output directory structure mirrors the input directory structure by using relative_to and creating necessary parent directories.
-
Modern Python Features: Leveraged list comprehensions, Path from pathlib, and f-strings for cleaner and more readable code.
Notes:
-
Dependencies: Ensure that Config, app, and ImageProcessor are properly defined in your codebase, as they are referenced in this function.
-
Logging: Replace the print statements in log_error with a proper logging framework if needed.
-
Temporary Folder: The create_temp_folder function currently creates a folder named "temp". Modify this as per your application's requirements or use Python's tempfile module for more robust temporary directory management.
-
Thread Pool Size: The ThreadPoolExecutor is initialized without specifying the number of threads, which defaults to the number of processors on the machine. You can adjust this by specifying the max_workers parameter if necessary.
This refactored function should seamlessly handle the resizing of multiple images, maintaining clarity and efficiency.