Untitled

 avatar
unknown
plain_text
5 months ago
9.4 kB
10
Indexable
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttk
from PIL import Image, ImageTk


class ImageResizerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Image Resizer")
        self.root.geometry("1200x800")
        self.root.configure(bg="#f0f0f0")

        # Use ttk Style to set a modern theme
        style = ttk.Style()
        style.theme_use("clam")
        style.configure("TFrame", background="#f0f0f0")
        style.configure("TLabel", background="#f0f0f0", font=("Helvetica", 12))
        style.configure("TButton", padding=10, font=("Helvetica", 12, "bold"), foreground="#ffffff")
        style.map("TButton",
                  background=[("active", "#1e90ff"), ("!active", "#0073e6")],
                  relief=[("pressed", "groove"), ("!pressed", "flat")])

        self.images = []  # List of loaded images
        self.image_paths = []  # List of image paths
        self.current_image_index = None

        # Main Frame
        main_frame = ttk.Frame(root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # Upload button
        self.upload_btn = ttk.Button(main_frame, text="Upload Images", command=self.upload_images)
        self.upload_btn.grid(row=0, column=0, pady=10, sticky=tk.W)

        # Thumbnails frame
        self.thumbnail_frame = ttk.Frame(main_frame)
        self.thumbnail_frame.grid(row=1, column=0, columnspan=3, pady=10, sticky=tk.W)

        # Canvas for image preview with border
        self.canvas_frame = ttk.Frame(main_frame, width=400, height=400, relief="sunken", borderwidth=2)
        self.canvas_frame.grid(row=2, column=0, columnspan=3, pady=10)
        self.canvas = tk.Canvas(self.canvas_frame, width=350, height=350, bg="white", highlightthickness=0)
        self.canvas.pack()

        # Resize controls frame
        controls_frame = ttk.Frame(main_frame, padding="10")
        controls_frame.grid(row=3, column=0, columnspan=3, pady=10)

        # Width and Height Labels and Entries
        self.width_label = ttk.Label(controls_frame, text="Width:")
        self.width_label.grid(row=0, column=0, sticky=tk.W, padx=5)
        self.width_entry = ttk.Entry(controls_frame, width=10)
        self.width_entry.grid(row=0, column=1, padx=5)
        self.width_entry.bind("<KeyRelease>", self.update_from_width)

        self.height_label = ttk.Label(controls_frame, text="Height:")
        self.height_label.grid(row=1, column=0, sticky=tk.W, padx=5)
        self.height_entry = ttk.Entry(controls_frame, width=10)
        self.height_entry.grid(row=1, column=1, padx=5)
        self.height_entry.bind("<KeyRelease>", self.update_from_height)

        # Resize Percentage
        self.percentage_label = ttk.Label(controls_frame, text="Resize Percentage:")
        self.percentage_label.grid(row=2, column=0, sticky=tk.W, padx=5)
        self.percentage_entry = ttk.Entry(controls_frame, width=10)
        self.percentage_entry.insert(0, "100")  # Set default percentage to 100%
        self.percentage_entry.grid(row=2, column=1, padx=5)
        self.percentage_entry.bind("<KeyRelease>", self.update_dimensions_from_percentage)

        # Resize button with modern styling
        self.resize_btn = ttk.Button(main_frame, text="Resize Image", command=self.resize_image, style="TButton")
        self.resize_btn.grid(row=4, column=0, pady=10, sticky=tk.W)

        # Download button with modern styling
        self.download_btn = ttk.Button(main_frame, text="Download Image", command=self.download_image, style="TButton")
        self.download_btn.grid(row=4, column=1, pady=10, sticky=tk.W)

    def upload_images(self):
        file_paths = filedialog.askopenfilenames(filetypes=[("Image files", "*.jpg;*.jpeg;*.png;*.bmp;*.tiff")])
        if file_paths:
            for file_path in file_paths:
                self.image_paths.append(file_path)
                self.images.append(Image.open(file_path))
                self.add_thumbnail(len(self.images) - 1)

    def add_thumbnail(self, index):
        img = self.images[index].copy()
        img.thumbnail((150, 150))
        tk_img = ImageTk.PhotoImage(img)

        # Create a button with the thumbnail image
        thumb_button = tk.Button(self.thumbnail_frame, image=tk_img, command=lambda idx=index: self.on_thumbnail_click(idx))
        thumb_button.image = tk_img  # Keep a reference to avoid garbage collection
        thumb_button.grid(row=index // 5, column=index % 5, padx=10, pady=10)

        # Overlay the width and height text on each thumbnail
        width, height = self.images[index].size
        dimension_label = tk.Label(self.thumbnail_frame, text=f"{width}x{height}", font=("Helvetica", 8), bg="white")
        dimension_label.place(in_=thumb_button, relx=0.5, rely=0.9, anchor="center")

    def on_thumbnail_click(self, index):
        self.current_image_index = index
        self.show_image(index)
        self.update_resize_fields(index)

    def show_image(self, index):
        if 0 <= index < len(self.images):
            img_copy = self.images[index].copy()
            img_copy.thumbnail((350, 350))
            self.tk_image = ImageTk.PhotoImage(img_copy)
            self.canvas.delete("all")
            self.canvas.create_image(175, 175, image=self.tk_image, anchor="center")

    def update_resize_fields(self, index):
        # Set width and height text fields with original dimensions
        if 0 <= index < len(self.images):
            image = self.images[index]
            self.width_entry.delete(0, tk.END)
            self.width_entry.insert(0, str(image.width))

            self.height_entry.delete(0, tk.END)
            self.height_entry.insert(0, str(image.height))

            # Set percentage to 100% for the selected image
            self.percentage_entry.delete(0, tk.END)
            self.percentage_entry.insert(0, "100")

    def update_dimensions_from_percentage(self, event):
        if self.current_image_index is not None:
            try:
                percentage = float(self.percentage_entry.get()) / 100.0
                image = self.images[self.current_image_index]
                new_width = int(image.width * percentage)
                new_height = int(image.height * percentage)

                self.width_entry.delete(0, tk.END)
                self.width_entry.insert(0, str(new_width))

                self.height_entry.delete(0, tk.END)
                self.height_entry.insert(0, str(new_height))
            except ValueError:
                pass

    def update_from_width(self, event):
        if self.current_image_index is not None:
            try:
                new_width = int(self.width_entry.get())
                image = self.images[self.current_image_index]
                percentage = new_width / image.width
                new_height = int(image.height * percentage)

                self.height_entry.delete(0, tk.END)
                self.height_entry.insert(0, str(new_height))

                self.percentage_entry.delete(0, tk.END)
                self.percentage_entry.insert(0, str(int(percentage * 100)))
            except ValueError:
                pass

    def update_from_height(self, event):
        if self.current_image_index is not None:
            try:
                new_height = int(self.height_entry.get())
                image = self.images[self.current_image_index]
                percentage = new_height / image.height
                new_width = int(image.width * percentage)

                self.width_entry.delete(0, tk.END)
                self.width_entry.insert(0, str(new_width))

                self.percentage_entry.delete(0, tk.END)
                self.percentage_entry.insert(0, str(int(percentage * 100)))
            except ValueError:
                pass

    def resize_image(self):
        if self.current_image_index is not None:
            width = self.width_entry.get()
            height = self.height_entry.get()

            if width and height:
                try:
                    width = int(width)
                    height = int(height)
                    self.images[self.current_image_index] = self.images[self.current_image_index].resize((width, height), Image.LANCZOS)

                    # Display success message
                    messagebox.showinfo("Success", "Image resized successfully.")
                    self.show_image(self.current_image_index)
                except ValueError:
                    messagebox.showerror("Error", "Invalid width or height values.")

    def download_image(self):
        if self.current_image_index is not None:
            save_path = filedialog.asksaveasfilename(defaultextension=".png",
                                                     filetypes=[("PNG files", "*.png"),
                                                                ("JPEG files", "*.jpg"),
                                                                ("All files", "*.*")])
            if save_path:
                self.images[self.current_image_index].save(save_path)


if __name__ == "__main__":
    root = tk.Tk()
    app = ImageResizerApp(root)
    root.mainloop()
Editor is loading...
Leave a Comment