Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- from tkinter import filedialog, messagebox, Label, Scrollbar, simpledialog
- from PIL import Image, ImageTk
- import sqlite3
- import io
- import os
- import ctypes # For setting the desktop wallpaper on Windows
- import re
- # Natural sorting function
- def natural_sort_key(s):
- return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', s)]
- # Set a predefined password
- DATABASE_PASSWORD = "123"
- current_db_path = "ImagesData.db" # Default database path
- current_image_data = None # Variable to store the current image data
- # Prompt for a password before proceeding
- def authenticate():
- password = simpledialog.askstring("Password", "Enter database password:", show="*")
- if password != DATABASE_PASSWORD:
- messagebox.showerror("Error", "Incorrect password!")
- root.destroy() # Close the application if the password is incorrect
- # Connect to the SQLite database and create the table if it doesn’t exist
- def connect_db(db_path):
- conn = sqlite3.connect(db_path)
- cursor = conn.cursor()
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS images (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT UNIQUE,
- image BLOB
- )
- """)
- conn.commit()
- conn.close()
- # Load images from the current database, ordered by name with natural sorting
- def load_images():
- image_list.delete(0, tk.END)
- conn = sqlite3.connect(current_db_path)
- cursor = conn.cursor()
- cursor.execute("SELECT name FROM images")
- results = [row[0] for row in cursor.fetchall()]
- conn.close()
- # Sort results using natural order (e.g., 1, 2, 10 instead of 1, 10, 2)
- results.sort(key=natural_sort_key)
- for name in results:
- image_list.insert(tk.END, name)
- # Add a new image to the current database
- def add_image():
- name = name_entry.get().strip()
- file_path = filedialog.askopenfilename(title="Select Image", filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.bmp")])
- if name and file_path:
- try:
- with open(file_path, "rb") as file:
- image_data = file.read()
- conn = sqlite3.connect(current_db_path)
- cursor = conn.cursor()
- cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
- conn.commit()
- conn.close()
- messagebox.showinfo("Success", "Image added successfully!")
- name_entry.delete(0, tk.END)
- load_images()
- except sqlite3.IntegrityError:
- messagebox.showerror("Error", "Image name already exists.")
- else:
- messagebox.showwarning("Input Error", "Please enter a name and select an image.")
- # Add all images from a folder to the database
- def add_images_from_folder():
- folder_path = filedialog.askdirectory(title="Select Folder")
- if folder_path:
- conn = sqlite3.connect(current_db_path)
- cursor = conn.cursor()
- for filename in os.listdir(folder_path):
- if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
- name = os.path.splitext(filename)[0]
- file_path = os.path.join(folder_path, filename)
- try:
- with open(file_path, "rb") as file:
- image_data = file.read()
- cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
- except sqlite3.IntegrityError:
- # Skip if image name already exists
- continue
- conn.commit()
- conn.close()
- messagebox.showinfo("Success", "All images added successfully!")
- load_images()
- # Search for an image by name
- def search_image():
- name = search_entry.get().strip()
- if name:
- conn = sqlite3.connect(current_db_path)
- cursor = conn.cursor()
- cursor.execute("SELECT image FROM images WHERE name = ?", (name,))
- result = cursor.fetchone()
- conn.close()
- if result:
- show_image(result[0])
- else:
- messagebox.showinfo("Not Found", "Image not found.")
- else:
- messagebox.showwarning("Input Error", "Please enter an image name to search.")
- # Show image in label with fit-to-screen functionality
- def show_image(image_data):
- global current_image_data
- current_image_data = image_data # Update current image data
- image = Image.open(io.BytesIO(image_data))
- image.thumbnail((600, 600)) # Resize to fit within 600x600 pixels
- photo = ImageTk.PhotoImage(image)
- image_label.config(image=photo)
- image_label.image = photo # Keep reference
- # Display the selected image from the list
- def display_image_content(event):
- try:
- selected_name = image_list.get(image_list.curselection())
- conn = sqlite3.connect(current_db_path)
- cursor = conn.cursor()
- cursor.execute("SELECT image FROM images WHERE name = ?", (selected_name,))
- result = cursor.fetchone()
- conn.close()
- if result:
- show_image(result[0])
- except tk.TclError:
- pass # No item selected
- # Save the displayed image to a file
- def save_image():
- if current_image_data:
- save_path = filedialog.asksaveasfilename(defaultextension=".png",
- filetypes=[("PNG files", "*.png"), ("JPEG files", "*.jpg"), ("All files", "*.*")])
- if save_path:
- with open(save_path, "wb") as file:
- file.write(current_image_data)
- messagebox.showinfo("Saved", "Image saved successfully!")
- else:
- messagebox.showwarning("No Image", "No image loaded to save.")
- # Delete the selected image from the database
- def delete_image():
- if image_list.curselection():
- selected_name = image_list.get(image_list.curselection())
- confirm = messagebox.askyesno("Confirm Delete", f"Are you sure you want to delete '{selected_name}'?")
- if confirm:
- conn = sqlite3.connect(current_db_path)
- cursor = conn.cursor()
- cursor.execute("DELETE FROM images WHERE name = ?", (selected_name,))
- conn.commit()
- conn.close()
- messagebox.showinfo("Success", "Image deleted successfully!")
- load_images() # Refresh the image list
- image_label.config(image="") # Clear the image display
- else:
- messagebox.showwarning("Selection Error", "Please select an image first to delete.")
- # Function to open and browse a new database, updating the image list
- def browse_new_database():
- global current_db_path
- db_path = filedialog.askopenfilename(title="Select Database", filetypes=[("SQLite Database", "*.db")])
- if db_path:
- current_db_path = db_path # Update the path to the new database
- connect_db(current_db_path) # Connect to and set up the new database
- load_images() # Load images from the new database
- messagebox.showinfo("Database Loaded", f"Connected to new database: {os.path.basename(current_db_path)}")
- # Function to set the displayed image as the desktop wallpaper
- def set_as_desktop_wallpaper():
- if current_image_data:
- # Save the current image to a temporary file
- temp_path = os.path.join(os.getenv("TEMP"), "temp_wallpaper.bmp")
- with open(temp_path, "wb") as file:
- file.write(current_image_data)
- # Set the wallpaper
- ctypes.windll.user32.SystemParametersInfoW(20, 0, temp_path, 3)
- messagebox.showinfo("Wallpaper Set", "Image set as desktop wallpaper!")
- else:
- messagebox.showwarning("No Image", "No image loaded to set as wallpaper.")
- # GUI Setup
- root = tk.Tk()
- root.title("Najeeb Image Database")
- root.geometry("900x640")
- root.configure(bg="#f0f0f5")
- # Authenticate first
- authenticate()
- # GUI Widgets
- style_label = {"bg": "#f0f0f5", "fg": "#333333", "font": ("Arial", 11)}
- style_button = {"bg": "#4CAF50", "fg": "white", "font": ("Arial", 10, "bold"), "width": 14, "padx": 2, "pady": 2}
- # Top Row: Add Image, Search
- tk.Label(root, text="Add Picture:", **style_label).grid(row=0, column=0, padx=2, pady=2, sticky="w")
- name_entry = tk.Entry(root, width=75, font=("Arial", 11))
- name_entry.grid(row=0, column=1, padx=2, pady=2, sticky="w")
- add_button = tk.Button(root, text="Add Image", command=add_image, **style_button)
- add_button.grid(row=0, column=2, padx=2, pady=2, sticky="w")
- # Search Entry and Button
- search_entry = tk.Entry(root, width=75, font=("Arial", 11))
- search_entry.grid(row=1, column=1, padx=2, pady=2, sticky="w")
- search_button = tk.Button(root, text="Search", command=search_image, **style_button)
- search_button.grid(row=1, column=2, padx=2, pady=2, sticky="w")
- # Show All Images, Browse New Database Buttons
- show_all_button = tk.Button(root, text="Show All Images", command=load_images, **style_button)
- show_all_button.grid(row=1, column=0, padx=5, pady=5, sticky="w")
- add_folder_button = tk.Button(root, text="Add Images Folder", command=add_images_from_folder, **style_button)
- add_folder_button.grid(row=3, column=2, padx=5, pady=5, sticky="w")
- # Save And Delete And Browse Button
- save_button = tk.Button(root, text="Save Image", command=save_image, **style_button)
- save_button.grid(row=4, column=2, padx=5, pady=2, sticky="w")
- delete_button = tk.Button(root, text="Delete", command=delete_image, **style_button)
- delete_button.grid(row=5, column=2, padx=5, pady=2, sticky="w")
- browse_new_db_button = tk.Button(root, text="Browse Database", command=browse_new_database, **style_button)
- browse_new_db_button.grid(row=6, column=2, padx=5, pady=2, sticky="w")
- # Add the "Set as Desktop" button in the GUI setup
- set_desktop_button = tk.Button(root, text="Set as Desktop", command=set_as_desktop_wallpaper, **style_button)
- set_desktop_button.grid(row=7, column=2, padx=5, pady=5, sticky="w")
- # Image List
- list_frame = tk.Frame(root)
- list_frame.grid(row=2, column=0, rowspan=6, padx=5, pady=5, sticky="n")
- image_list = tk.Listbox(list_frame, width=16, height=30, font=("Arial", 11))
- image_list.pack(side="left", fill="y")
- scrollbar = Scrollbar(list_frame, orient="vertical", command=image_list.yview)
- scrollbar.pack(side="right", fill="y")
- image_list.config(yscrollcommand=scrollbar.set)
- image_list.bind("<<ListboxSelect>>", display_image_content)
- # Image Display Label
- image_frame = tk.Frame(root)
- image_frame.grid(row=2, column=1, rowspan=6, padx=5, pady=5, sticky="nw")
- image_label = Label(image_frame, bg="#ffffff")
- image_label.pack()
- # Database connection on start-up
- connect_db(current_db_path)
- load_images() # Load images from the default database
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement