Advertisement
Najeebsk

IMAGE-DATA-ZOOM.pyw

Nov 6th, 2024 (edited)
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.11 KB | None | 0 0
  1. import tkinter as tk
  2. from tkinter import filedialog, messagebox, Label, Scrollbar, simpledialog
  3. from PIL import Image, ImageTk
  4. import sqlite3
  5. import io
  6. import os
  7. import ctypes  # For setting the desktop wallpaper on Windows
  8.  
  9. # Set a predefined password
  10. DATABASE_PASSWORD = "123456"
  11. current_db_path = "ImagesData.db"  # Default database path
  12. current_image_data = None  # Variable to store the current image data
  13. current_image = None  # Variable to store the current PIL image
  14. zoom_factor = 1.0  # Initialize zoom factor
  15.  
  16. # Prompt for a password before proceeding
  17. def authenticate():
  18.     password = simpledialog.askstring("Password", "Enter database password:", show="*")
  19.     if password != DATABASE_PASSWORD:
  20.         messagebox.showerror("Error", "Incorrect password!")
  21.         root.destroy()  # Close the application if the password is incorrect
  22.  
  23. # Connect to the SQLite database and create the table if it doesn’t exist
  24. def connect_db(db_path):
  25.     conn = sqlite3.connect(db_path)
  26.     cursor = conn.cursor()
  27.     cursor.execute("""
  28.    CREATE TABLE IF NOT EXISTS images (
  29.        id INTEGER PRIMARY KEY AUTOINCREMENT,
  30.        name TEXT UNIQUE,
  31.        image BLOB
  32.    )
  33.    """)
  34.     conn.commit()
  35.     conn.close()
  36.  
  37. # Load images from the current database and display them in the list
  38. def load_images():
  39.     image_list.delete(0, tk.END)
  40.     conn = sqlite3.connect(current_db_path)
  41.     cursor = conn.cursor()
  42.     cursor.execute("SELECT name FROM images")
  43.     results = cursor.fetchall()
  44.     conn.close()
  45.     for row in results:
  46.         image_list.insert(tk.END, row[0])
  47.  
  48. # Add a new image to the current database
  49. def add_image():
  50.     name = name_entry.get().strip()
  51.     file_path = filedialog.askopenfilename(title="Select Image", filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.bmp")])
  52.    
  53.     if name and file_path:
  54.         try:
  55.             with open(file_path, "rb") as file:
  56.                 image_data = file.read()
  57.             conn = sqlite3.connect(current_db_path)
  58.             cursor = conn.cursor()
  59.             cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
  60.             conn.commit()
  61.             conn.close()
  62.             messagebox.showinfo("Success", "Image added successfully!")
  63.             name_entry.delete(0, tk.END)
  64.             load_images()
  65.         except sqlite3.IntegrityError:
  66.             messagebox.showerror("Error", "Image name already exists.")
  67.     else:
  68.         messagebox.showwarning("Input Error", "Please enter a name and select an image.")
  69.  
  70. # Add all images from a folder to the database
  71. def add_images_from_folder():
  72.     folder_path = filedialog.askdirectory(title="Select Folder")
  73.     if folder_path:
  74.         conn = sqlite3.connect(current_db_path)
  75.         cursor = conn.cursor()
  76.         for filename in os.listdir(folder_path):
  77.             if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
  78.                 name = os.path.splitext(filename)[0]
  79.                 file_path = os.path.join(folder_path, filename)
  80.                 try:
  81.                     with open(file_path, "rb") as file:
  82.                         image_data = file.read()
  83.                     cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
  84.                 except sqlite3.IntegrityError:
  85.                     # Skip if image name already exists
  86.                     continue
  87.         conn.commit()
  88.         conn.close()
  89.         messagebox.showinfo("Success", "All images added successfully!")
  90.         load_images()
  91.  
  92. # Search for an image by name
  93. def search_image():
  94.     name = search_entry.get().strip()
  95.     if name:
  96.         conn = sqlite3.connect(current_db_path)
  97.         cursor = conn.cursor()
  98.         cursor.execute("SELECT image FROM images WHERE name = ?", (name,))
  99.         result = cursor.fetchone()
  100.         conn.close()
  101.         if result:
  102.             show_image(result[0])
  103.         else:
  104.             messagebox.showinfo("Not Found", "Image not found.")
  105.     else:
  106.         messagebox.showwarning("Input Error", "Please enter an image name to search.")        
  107.  
  108. # Show image in label with fit-to-screen functionality
  109. def show_image(image_data):
  110.     global current_image_data, current_image, zoom_factor
  111.     current_image_data = image_data  # Update current image data
  112.     current_image = Image.open(io.BytesIO(image_data))
  113.     display_image()  # Call display_image to show the current image with zoom factor
  114.  
  115. def display_image():
  116.     global current_image, zoom_factor
  117.     if current_image:
  118.         # Resize image based on the zoom factor
  119.         image_size = (int(current_image.width * zoom_factor), int(current_image.height * zoom_factor))
  120.         image_resized = current_image.resize(image_size, Image.ANTIALIAS)
  121.         photo = ImageTk.PhotoImage(image_resized)
  122.         image_label.config(image=photo)
  123.         image_label.image = photo  # Keep reference
  124.  
  125. # Display the selected image from the list
  126. def display_image_content(event):
  127.     try:
  128.         selected_name = image_list.get(image_list.curselection())
  129.         conn = sqlite3.connect(current_db_path)
  130.         cursor = conn.cursor()
  131.         cursor.execute("SELECT image FROM images WHERE name = ?", (selected_name,))
  132.         result = cursor.fetchone()
  133.         conn.close()
  134.         if result:
  135.             show_image(result[0])
  136.     except tk.TclError:
  137.         pass  # No item selected
  138.  
  139. # Save the displayed image to a file
  140. def save_image():
  141.     if current_image_data:
  142.         save_path = filedialog.asksaveasfilename(defaultextension=".png",
  143.                                                  filetypes=[("PNG files", "*.png"), ("JPEG files", "*.jpg"), ("All files", "*.*")])
  144.         if save_path:
  145.             with open(save_path, "wb") as file:
  146.                 file.write(current_image_data)
  147.             messagebox.showinfo("Saved", "Image saved successfully!")
  148.     else:
  149.         messagebox.showwarning("No Image", "No image loaded to save.")
  150.  
  151. # Delete the selected image from the database
  152. def delete_image():
  153.     if image_list.curselection():
  154.         selected_name = image_list.get(image_list.curselection())
  155.         confirm = messagebox.askyesno("Confirm Delete", f"Are you sure you want to delete '{selected_name}'?")
  156.         if confirm:
  157.             conn = sqlite3.connect(current_db_path)
  158.             cursor = conn.cursor()
  159.             cursor.execute("DELETE FROM images WHERE name = ?", (selected_name,))
  160.             conn.commit()
  161.             conn.close()
  162.             messagebox.showinfo("Success", "Image deleted successfully!")
  163.             load_images()  # Refresh the image list
  164.             image_label.config(image="")  # Clear the image display
  165.     else:
  166.         messagebox.showwarning("Selection Error", "Please select an image first to delete.")
  167.  
  168. # Function to open and browse a new database, updating the image list
  169. def browse_new_database():
  170.     global current_db_path
  171.     db_path = filedialog.askopenfilename(title="Select Database", filetypes=[("SQLite Database", "*.db")])
  172.     if db_path:
  173.         current_db_path = db_path  # Update the path to the new database
  174.         connect_db(current_db_path)  # Connect to and set up the new database
  175.         load_images()  # Load images from the new database
  176.         messagebox.showinfo("Database Loaded", f"Connected to new database: {os.path.basename(current_db_path)}")
  177.  
  178. # Function to set the displayed image as the desktop wallpaper
  179. def set_as_desktop_wallpaper():
  180.     if current_image_data:
  181.         # Save the current image to a temporary file
  182.         temp_path = os.path.join(os.getenv("TEMP"), "temp_wallpaper.bmp")
  183.         with open(temp_path, "wb") as file:
  184.             file.write(current_image_data)
  185.  
  186.         # Set the wallpaper
  187.         ctypes.windll.user32.SystemParametersInfoW(20, 0, temp_path, 3)
  188.         messagebox.showinfo("Wallpaper Set", "Image set as desktop wallpaper!")
  189.     else:
  190.         messagebox.showwarning("No Image", "No image loaded to set as wallpaper.")
  191.  
  192. # Zoom in and out with mouse wheel
  193. def zoom(event):
  194.     global zoom_factor
  195.     if event.delta > 0:  # Zoom in
  196.         zoom_factor *= 1.1
  197.     else:  # Zoom out
  198.         zoom_factor /= 1.1
  199.     display_image()  # Refresh the displayed image with the new zoom factor
  200.  
  201. # GUI Setup
  202. root = tk.Tk()
  203. root.title("Najeeb Image Database")
  204. root.geometry("900x640")
  205. root.configure(bg="#f0f0f5")
  206.  
  207. # Authenticate first
  208. authenticate()
  209.  
  210. # GUI Widgets
  211. style_label = {"bg": "#f0f0f5", "fg": "#333333", "font": ("Arial", 11)}
  212. style_button = {"bg": "#4CAF50", "fg": "white", "font": ("Arial", 10, "bold"), "width": 14, "padx": 2, "pady": 2}
  213.  
  214. # Top Row: Add Image, Search
  215. tk.Label(root, text="Add Picture:", **style_label).grid(row=0, column=0, padx=2, pady=2, sticky="w")
  216. name_entry = tk.Entry(root, width=75, font=("Arial", 11))
  217. name_entry.grid(row=0, column=1, padx=2, pady=2, sticky="w")
  218.  
  219. add_image_button = tk.Button(root, text="Add Image", command=add_image, **style_button)
  220. add_image_button.grid(row=0, column=2, padx=2, pady=2)
  221.  
  222. tk.Label(root, text="Search by Name:", **style_label).grid(row=1, column=0, padx=2, pady=2, sticky="w")
  223. search_entry = tk.Entry(root, width=75, font=("Arial", 11))
  224. search_entry.grid(row=1, column=1, padx=2, pady=2, sticky="w")
  225.  
  226. search_button = tk.Button(root, text="Search", command=search_image, **style_button)
  227. search_button.grid(row=1, column=2, padx=2, pady=2)
  228.  
  229. add_folder_button = tk.Button(root, text="Add Images from Folder", command=add_images_from_folder, bg="#4CAF50", fg="white", font=("Arial", 10, "bold"), width=20, padx=5, pady=2)
  230. add_folder_button.grid(row=2, column=0, padx=2, pady=2, sticky="w", columnspan=3)
  231.  
  232. # Browse New Database
  233. browse_db_button = tk.Button(root, text="Browse Database", command=browse_new_database, **style_button)
  234. browse_db_button.grid(row=2, column=2, padx=1, pady=1, sticky="w", columnspan=3)
  235.  
  236.  
  237. # Middle Row: Image List
  238. image_list = tk.Listbox(root, width=90, height=10, font=("Arial", 11))
  239. image_list.grid(row=3, column=0, columnspan=3, padx=2, pady=2, sticky="nsew")
  240. image_list.bind("<Double-Button-1>", display_image_content)
  241.  
  242. scrollbar = Scrollbar(root)
  243. scrollbar.grid(row=3, column=3, sticky="ns")
  244. image_list.config(yscrollcommand=scrollbar.set)
  245. scrollbar.config(command=image_list.yview)
  246.  
  247. # Image Display
  248. image_label = Label(root, bg="white")
  249. image_label.grid(row=4, column=0, columnspan=3, padx=2, pady=2, sticky="nsew")
  250.  
  251. # Bottom Row: Save, Delete, Set Wallpaper
  252. save_button = tk.Button(root, text="Save Image", command=save_image, **style_button)
  253. save_button.grid(row=5, column=0, padx=2, pady=2)
  254.  
  255. delete_button = tk.Button(root, text="Delete Selected", command=delete_image, **style_button)
  256. delete_button.grid(row=5, column=1, padx=2, pady=2)
  257.  
  258. set_wallpaper_button = tk.Button(root, text="Set as Wallpaper", command=set_as_desktop_wallpaper, **style_button)
  259. set_wallpaper_button.grid(row=5, column=2, padx=2, pady=2)
  260.  
  261.  
  262. # Make sure the middle row expands
  263. root.grid_rowconfigure(3, weight=1)
  264. root.grid_columnconfigure(0, weight=1)
  265. root.grid_columnconfigure(1, weight=1)
  266. root.grid_columnconfigure(2, weight=1)
  267.  
  268. # Bind mouse wheel event for zooming
  269. root.bind("<MouseWheel>", zoom)
  270.  
  271. # Connect to the database
  272. connect_db(current_db_path)
  273. load_images()
  274.  
  275. root.mainloop()
  276.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement