Advertisement
Najeebsk

IMAGES-DATA2.0.pyw

Nov 11th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.67 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. import re
  9.  
  10. # Natural sorting function
  11. def natural_sort_key(s):
  12.     return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', s)]
  13.  
  14. # Set a predefined password
  15. DATABASE_PASSWORD = "123"
  16. current_db_path = "ImagesData.db"  # Default database path
  17. current_image_data = None  # Variable to store the current image data
  18.  
  19. # Prompt for a password before proceeding
  20. def authenticate():
  21.     password = simpledialog.askstring("Password", "Enter database password:", show="*")
  22.     if password != DATABASE_PASSWORD:
  23.         messagebox.showerror("Error", "Incorrect password!")
  24.         root.destroy()  # Close the application if the password is incorrect
  25.  
  26. # Connect to the SQLite database and create the table if it doesn’t exist
  27. def connect_db(db_path):
  28.     conn = sqlite3.connect(db_path)
  29.     cursor = conn.cursor()
  30.     cursor.execute("""
  31.    CREATE TABLE IF NOT EXISTS images (
  32.        id INTEGER PRIMARY KEY AUTOINCREMENT,
  33.        name TEXT UNIQUE,
  34.        image BLOB
  35.    )
  36.    """)
  37.     conn.commit()
  38.     conn.close()
  39.  
  40. # Load images from the current database, ordered by name with natural sorting
  41. def load_images():
  42.     image_list.delete(0, tk.END)
  43.     conn = sqlite3.connect(current_db_path)
  44.     cursor = conn.cursor()
  45.     cursor.execute("SELECT name FROM images")
  46.     results = [row[0] for row in cursor.fetchall()]
  47.     conn.close()
  48.  
  49.     # Sort results using natural order (e.g., 1, 2, 10 instead of 1, 10, 2)
  50.     results.sort(key=natural_sort_key)
  51.    
  52.     for name in results:
  53.         image_list.insert(tk.END, name)
  54.  
  55. # Add a new image to the current database
  56. def add_image():
  57.     name = name_entry.get().strip()
  58.     file_path = filedialog.askopenfilename(title="Select Image", filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.bmp")])
  59.    
  60.     if name and file_path:
  61.         try:
  62.             with open(file_path, "rb") as file:
  63.                 image_data = file.read()
  64.             conn = sqlite3.connect(current_db_path)
  65.             cursor = conn.cursor()
  66.             cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
  67.             conn.commit()
  68.             conn.close()
  69.             messagebox.showinfo("Success", "Image added successfully!")
  70.             name_entry.delete(0, tk.END)
  71.             load_images()
  72.         except sqlite3.IntegrityError:
  73.             messagebox.showerror("Error", "Image name already exists.")
  74.     else:
  75.         messagebox.showwarning("Input Error", "Please enter a name and select an image.")
  76.  
  77. # Add all images from a folder to the database
  78. def add_images_from_folder():
  79.     folder_path = filedialog.askdirectory(title="Select Folder")
  80.     if folder_path:
  81.         conn = sqlite3.connect(current_db_path)
  82.         cursor = conn.cursor()
  83.         for filename in os.listdir(folder_path):
  84.             if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
  85.                 name = os.path.splitext(filename)[0]
  86.                 file_path = os.path.join(folder_path, filename)
  87.                 try:
  88.                     with open(file_path, "rb") as file:
  89.                         image_data = file.read()
  90.                     cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
  91.                 except sqlite3.IntegrityError:
  92.                     # Skip if image name already exists
  93.                     continue
  94.         conn.commit()
  95.         conn.close()
  96.         messagebox.showinfo("Success", "All images added successfully!")
  97.         load_images()
  98.  
  99. # Search for an image by name
  100. def search_image():
  101.     name = search_entry.get().strip()
  102.     if name:
  103.         conn = sqlite3.connect(current_db_path)
  104.         cursor = conn.cursor()
  105.         cursor.execute("SELECT image FROM images WHERE name = ?", (name,))
  106.         result = cursor.fetchone()
  107.         conn.close()
  108.         if result:
  109.             show_image(result[0])
  110.         else:
  111.             messagebox.showinfo("Not Found", "Image not found.")
  112.     else:
  113.         messagebox.showwarning("Input Error", "Please enter an image name to search.")        
  114.  
  115. # Show image in label with fit-to-screen functionality
  116. def show_image(image_data):
  117.     global current_image_data
  118.     current_image_data = image_data  # Update current image data
  119.     image = Image.open(io.BytesIO(image_data))
  120.     image.thumbnail((600, 600))  # Resize to fit within 600x600 pixels
  121.     photo = ImageTk.PhotoImage(image)
  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.  
  193. # GUI Setup
  194. root = tk.Tk()
  195. root.title("Najeeb Image Database")
  196. root.geometry("900x640")
  197. root.configure(bg="#f0f0f5")
  198.  
  199. # Authenticate first
  200. authenticate()
  201.  
  202. # GUI Widgets
  203. style_label = {"bg": "#f0f0f5", "fg": "#333333", "font": ("Arial", 11)}
  204. style_button = {"bg": "#4CAF50", "fg": "white", "font": ("Arial", 10, "bold"), "width": 14, "padx": 2, "pady": 2}
  205.  
  206. # Top Row: Add Image, Search
  207. tk.Label(root, text="Add Picture:", **style_label).grid(row=0, column=0, padx=2, pady=2, sticky="w")
  208. name_entry = tk.Entry(root, width=75, font=("Arial", 11))
  209. name_entry.grid(row=0, column=1, padx=2, pady=2, sticky="w")
  210.  
  211. add_button = tk.Button(root, text="Add Image", command=add_image, **style_button)
  212. add_button.grid(row=0, column=2, padx=2, pady=2, sticky="w")
  213.  
  214. # Search Entry and Button
  215. search_entry = tk.Entry(root, width=75, font=("Arial", 11))
  216. search_entry.grid(row=1, column=1, padx=2, pady=2, sticky="w")
  217.  
  218. search_button = tk.Button(root, text="Search", command=search_image, **style_button)
  219. search_button.grid(row=1, column=2, padx=2, pady=2, sticky="w")
  220.  
  221. # Show All Images, Browse New Database Buttons
  222. show_all_button = tk.Button(root, text="Show All Images", command=load_images, **style_button)
  223. show_all_button.grid(row=1, column=0, padx=5, pady=5, sticky="w")
  224.  
  225. add_folder_button = tk.Button(root, text="Add Images Folder", command=add_images_from_folder, **style_button)
  226. add_folder_button.grid(row=3, column=2, padx=5, pady=5, sticky="w")
  227.  
  228. # Save And Delete And Browse Button
  229. save_button = tk.Button(root, text="Save Image", command=save_image, **style_button)
  230. save_button.grid(row=4, column=2, padx=5, pady=2, sticky="w")
  231.  
  232. delete_button = tk.Button(root, text="Delete", command=delete_image, **style_button)
  233. delete_button.grid(row=5, column=2, padx=5, pady=2, sticky="w")
  234.  
  235. browse_new_db_button = tk.Button(root, text="Browse  Database", command=browse_new_database, **style_button)
  236. browse_new_db_button.grid(row=6, column=2, padx=5, pady=2, sticky="w")
  237.  
  238. # Add the "Set as Desktop" button in the GUI setup
  239. set_desktop_button = tk.Button(root, text="Set as Desktop", command=set_as_desktop_wallpaper, **style_button)
  240. set_desktop_button.grid(row=7, column=2, padx=5, pady=5, sticky="w")
  241.  
  242. # Image List
  243. list_frame = tk.Frame(root)
  244. list_frame.grid(row=2, column=0, rowspan=6, padx=5, pady=5, sticky="n")
  245. image_list = tk.Listbox(list_frame, width=16, height=30, font=("Arial", 11))
  246. image_list.pack(side="left", fill="y")
  247. scrollbar = Scrollbar(list_frame, orient="vertical", command=image_list.yview)
  248. scrollbar.pack(side="right", fill="y")
  249. image_list.config(yscrollcommand=scrollbar.set)
  250. image_list.bind("<<ListboxSelect>>", display_image_content)
  251.  
  252. # Image Display Label
  253. image_frame = tk.Frame(root)
  254. image_frame.grid(row=2, column=1, rowspan=6, padx=5, pady=5, sticky="nw")
  255. image_label = Label(image_frame, bg="#ffffff")
  256. image_label.pack()
  257.  
  258.  
  259. # Database connection on start-up
  260. connect_db(current_db_path)
  261. load_images()  # Load images from the default database
  262.  
  263. root.mainloop()
  264.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement