To address your needs, we'll create a Python script using Tkinter for creating the UI, and Pillow for image manipulation. This script will allow users to choose a directory containing images, display information about those images, and provide options for resizing them according to predefined presets, or a custom size with an optional proportional constraint.
Here's how the proposed solution will work:
- Folder and Image Selection: Users will select a folder containing images.
- Image Information Display: Total number of images and the first image's dimensions will be displayed.
- Resize Options: A dropdown menu allows users to select resizing presets or specify custom dimensions.
- Proportional Scaling: If enabled, resizing preserves the aspect ratio when a user changes one dimension.
- Progress and Control: A progress bar shows resizing operations, alongside
OK or CANCEL buttons for executing or terminating the operation.
Below is the fully integrated Python script:
import os
from PIL import Image
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
def validate_size(value):
"""Validate if the input is a positive integer."""
return value.isdigit() and int(value) > 0
class ImageResizerApp:
def __init__(self, root):
self.root = root
self.root.title("Image Resizer")
self.root.geometry("600x400")
self.image_paths = []
self.original_width = None
self.original_height = None
self.is_proportionate_checked = tk.BooleanVar(value=True)
self.directory_label = tk.Label(root, text="No folder selected", wraplength=400)
self.directory_label.pack(pady=10)
self.select_folder_button = tk.Button(root, text="Select Folder", command=self.select_folder)
self.select_folder_button.pack(pady=10)
self.info_label = tk.Label(root, text="", wraplength=450)
self.info_label.pack(pady=10)
self.resize_options = ["2X Downscale", "2X Upscale", "4X Downscale", "4X Upscale", "Custom"]
self.resize_var = tk.StringVar(value=self.resize_options[0])
self.resize_dropdown = ttk.Combobox(root, textvariable=self.resize_var, values=self.resize_options, state="readonly")
self.resize_dropdown.bind("<<ComboboxSelected>>", self.on_resize_option_change)
self.resize_dropdown.pack(pady=10)
self.custom_size_frame = tk.Frame(root)
self.custom_width_label = tk.Label(self.custom_size_frame, text="Width:")
self.custom_width_label.pack(side=tk.LEFT)
self.custom_width_entry = ttk.Entry(self.custom_size_frame, validate="key", validatecommand=(root.register(validate_size), "%P"))
self.custom_width_entry.pack(side=tk.LEFT, padx=5)
self.custom_height_label = tk.Label(self.custom_size_frame, text="Height:")
self.custom_height_label.pack(side=tk.LEFT)
self.custom_height_entry = ttk.Entry(self.custom_size_frame, validate="key", validatecommand=(root.register(validate_size), "%P"))
self.custom_height_entry.pack(side=tk.LEFT, padx=5)
self.proportional_checkbox = tk.Checkbutton(self.custom_size_frame, text="Proportional", variable=self.is_proportionate_checked)
self.proportional_checkbox.pack(side=tk.LEFT)
self.custom_height_entry.bind("<KeyRelease>", self.update_size_proportionally)
self.custom_width_entry.bind("<KeyRelease>", self.update_size_proportionally)
self.progress_bar = ttk.Progressbar(root, orient="horizontal", mode="determinate", length=400)
self.progress_bar.pack(pady=10)
self.button_frame = tk.Frame(root)
self.ok_button = tk.Button(self.button_frame, text="OK", command=self.process_images, state=tk.DISABLED)
self.ok_button.pack(side=tk.LEFT, padx=20)
self.cancel_button = tk.Button(self.button_frame, text="CANCEL", command=root.quit)
self.cancel_button.pack(side=tk.LEFT, padx=20)
self.button_frame.pack(pady=20)
def select_folder(self):
folder_path = filedialog.askdirectory()
if folder_path:
self.image_paths = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.lower().endswith(('png', 'jpg', 'jpeg'))]
if self.image_paths:
# Update UI on folder selection
self.directory_label.config(text=f"Selected Folder: {folder_path}")
self.display_image_info(self.image_paths[0])
self.ok_button.config(state=tk.NORMAL)
else:
messagebox.showerror("Error", "No images found in the selected folder.")
def display_image_info(self, first_image_path):
# Retrieve image size from the first image
with Image.open(first_image_path) as img:
self.original_width, self.original_height = img.size
self.info_label.config(text=f"Total images: {len(self.image_paths)}\nFirst image size: {self.original_width}x{self.original_height}")
def on_resize_option_change(self, event=None):
""" Show or hide custom size inputs based on the selected option """
if self.resize_var.get() == "Custom":
self.custom_size_frame.pack(pady=10)
self.custom_width_entry.delete(0, tk.END)
self.custom_height_entry.delete(0, tk.END)
self.custom_width_entry.insert(0, str(self.original_width))
self.custom_height_entry.insert(0, str(self.original_height))
else:
self.custom_size_frame.pack_forget()
def update_size_proportionally(self, event=None):
""" Update dimensions while maintaining aspect ratio """
if self.is_proportionate_checked.get():
try:
if event.widget == self.custom_width_entry and self.custom_width_entry.get():
width = int(self.custom_width_entry.get())
height = int((width / self.original_width) * self.original_height)
self.custom_height_entry.delete(0, tk.END)
self.custom_height_entry.insert(0, str(height))
elif event.widget == self.custom_height_entry and self.custom_height_entry.get():
height = int(self.custom_height_entry.get())
width = int((height / self.original_height) * self.original_width)
self.custom_width_entry.delete(0, tk.END)
self.custom_width_entry.insert(0, str(width))
except ValueError:
pass
def process_images(self):
# Prepare for resizing based on selected option
scale_factor = 1
if self.resize_var.get() == "2X Downscale":
scale_factor = 0.5
elif self.resize_var.get() == "2X Upscale":
scale_factor = 2
elif self.resize_var.get() == "4X Downscale":
scale_factor = 0.25
elif self.resize_var.get() == "4X Upscale":
scale_factor = 4
for index, image_path in enumerate(self.image_paths, start=1):
with Image.open(image_path) as img:
new_size = (
int(self.custom_width_entry.get()),
int(self.custom_height_entry.get())
) if self.resize_var.get() == "Custom" else (
int(img.width * scale_factor), int(img.height * scale_factor))
resized_img = img.resize(new_size, Image.ANTIALIAS)
resized_img.save(image_path)
self.update_progress(index / len(self.image_paths) * 100)
def update_progress(self, value):
self.progress_bar['value'] = value
self.root.update_idletasks()
if __name__ == "__main__":
root = tk.Tk()
app = ImageResizerApp(root)
root.mainloop()
Key Features of the Script:
- Folder Selection: Users can select a folder, and the script will process all valid image files within it.
- Image Information: Displays total number of images and size of the first image.
- Resize Options: Provides a dropdown menu with preset options and an option for custom resizing.
- Custom Resizing: Allows manual input for image dimensions, with a proportional option enabled by default.
- Progress Indicator: Shows progress as images are processed.
- Action Buttons:
OK to start resizing and CANCEL to exit.
Requirements:
- Ensure
Pillow is installed by running:
pip install Pillow
This script serves as a functional and comprehensive image resizer with various preset and customizable options, making batch image processing user-friendly. Adjust the script as necessary to fit additional requirements or preferences.