app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
import tkinter as tk from tkinter import filedialog, messagebox from PIL import Image, ImageTk def merge_images(image_paths, direction='horizontal'): images = [Image.open(img_path) for img_path in image_paths] if direction == 'horizontal': max_height = max(img.height for img in images) total_width = sum(img.width for img in images) merged_img = Image.new('RGB', (total_width, max_height)) x_offset = 0 for img in images: if img.height != max_height: img = img.resize((img.width, max_height)) merged_img.paste(img, (x_offset, 0)) x_offset += img.width elif direction == 'vertical': max_width = max(img.width for img in images) total_height = sum(img.height for img in images) merged_img = Image.new('RGB', (max_width, total_height)) y_offset = 0 for img in images: if img.width != max_width: img = img.resize((max_width, img.height)) merged_img.paste(img, (0, y_offset)) y_offset += img.height else: raise ValueError("Invalid direction. Use 'horizontal' or 'vertical'.") return merged_img def select_images(): filetypes = [("Image Files", "*.png;*.jpg;*.jpeg;*.bmp;*.gif")] files = filedialog.askopenfilenames(title="Select Images", filetypes=filetypes) if files: image_paths.clear() image_paths.extend(files) img_list_label.config(text=f"{len(image_paths)} images selected.") def merge_and_display(): if not image_paths: messagebox.showwarning("No Images", "Please select images to merge.") return direction = direction_var.get() try: merged_img = merge_images(image_paths, direction) except Exception as e: messagebox.showerror("Error", f"Failed to merge images:\n{e}") return # Resize for display display_img = merged_img.copy() display_img.thumbnail((600, 400)) tk_img = ImageTk.PhotoImage(display_img) img_label.config(image=tk_img) img_label.image = tk_img # Save output save_path = filedialog.asksaveasfilename( defaultextension=".png", filetypes=[("PNG Image", "*.png")], title="Save Merged Image" ) if save_path: merged_img.save(save_path) messagebox.showinfo("Saved", f"Merged image saved to:\n{save_path}") # Tkinter setup root = tk.Tk() root.title("Image Merger") root.geometry("700x600") image_paths = [] # Widgets direction_var = tk.StringVar(value='horizontal') tk.Label(root, text="Select merge direction:").pack(pady=5) tk.OptionMenu(root, direction_var, "horizontal", "vertical").pack() tk.Button(root, text="Select Images", command=select_images).pack(pady=10) img_list_label = tk.Label(root, text="No images selected.") img_list_label.pack() tk.Button(root, text="Merge and Save", command=merge_and_display).pack(pady=10) img_label = tk.Label(root) img_label.pack(pady=10, expand=True) root.mainloop() |