Advertisement
Najeebsk

IMAGES-DATA.pyw

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