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
- # Set a predefined password
- DATABASE_PASSWORD = "123456"
- current_db_path = "ImagesData.db" # Default database path
- current_image_data = None # Variable to store the current image data
- current_image = None # Variable to store the current PIL image
- zoom_factor = 1.0 # Initialize zoom factor
- # 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 and display them in the list
- 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 = cursor.fetchall()
- conn.close()
- for row in results:
- image_list.insert(tk.END, row[0])
- # 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, zoom_factor
- current_image_data = image_data # Update current image data
- current_image = Image.open(io.BytesIO(image_data))
- display_image() # Call display_image to show the current image with zoom factor
- def display_image():
- global current_image, zoom_factor
- if current_image:
- # Resize image based on the zoom factor
- image_size = (int(current_image.width * zoom_factor), int(current_image.height * zoom_factor))
- image_resized = current_image.resize(image_size, Image.ANTIALIAS)
- photo = ImageTk.PhotoImage(image_resized)
- 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.")
- # Zoom in and out with mouse wheel
- def zoom(event):
- global zoom_factor
- if event.delta > 0: # Zoom in
- zoom_factor *= 1.1
- else: # Zoom out
- zoom_factor /= 1.1
- display_image() # Refresh the displayed image with the new zoom factor
- # 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_image_button = tk.Button(root, text="Add Image", command=add_image, **style_button)
- add_image_button.grid(row=0, column=2, padx=2, pady=2)
- tk.Label(root, text="Search by Name:", **style_label).grid(row=1, column=0, padx=2, pady=2, sticky="w")
- 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)
- 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)
- add_folder_button.grid(row=2, column=0, padx=2, pady=2, sticky="w", columnspan=3)
- # Browse New Database
- browse_db_button = tk.Button(root, text="Browse Database", command=browse_new_database, **style_button)
- browse_db_button.grid(row=2, column=2, padx=1, pady=1, sticky="w", columnspan=3)
- # Middle Row: Image List
- image_list = tk.Listbox(root, width=90, height=10, font=("Arial", 11))
- image_list.grid(row=3, column=0, columnspan=3, padx=2, pady=2, sticky="nsew")
- image_list.bind("<Double-Button-1>", display_image_content)
- scrollbar = Scrollbar(root)
- scrollbar.grid(row=3, column=3, sticky="ns")
- image_list.config(yscrollcommand=scrollbar.set)
- scrollbar.config(command=image_list.yview)
- # Image Display
- image_label = Label(root, bg="white")
- image_label.grid(row=4, column=0, columnspan=3, padx=2, pady=2, sticky="nsew")
- # Bottom Row: Save, Delete, Set Wallpaper
- save_button = tk.Button(root, text="Save Image", command=save_image, **style_button)
- save_button.grid(row=5, column=0, padx=2, pady=2)
- delete_button = tk.Button(root, text="Delete Selected", command=delete_image, **style_button)
- delete_button.grid(row=5, column=1, padx=2, pady=2)
- set_wallpaper_button = tk.Button(root, text="Set as Wallpaper", command=set_as_desktop_wallpaper, **style_button)
- set_wallpaper_button.grid(row=5, column=2, padx=2, pady=2)
- # Make sure the middle row expands
- root.grid_rowconfigure(3, weight=1)
- root.grid_columnconfigure(0, weight=1)
- root.grid_columnconfigure(1, weight=1)
- root.grid_columnconfigure(2, weight=1)
- # Bind mouse wheel event for zooming
- root.bind("<MouseWheel>", zoom)
- # Connect to the database
- connect_db(current_db_path)
- load_images()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement