Untitled

raw code for DoW Badgnner
 avatar
unknown
python
a year ago
7.0 kB
37
Indexable
import os
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
import traceback

# --- Core Asset Creation Logic ---

BADGE_DIMS = (64, 64)
BANNER_DIMS = (64, 96)

def create_asset(image_path, output_dir, asset_type, log_callback=print):
    try:
        log_callback(f"Opening source image: {image_path}")
        source_image = Image.open(image_path)
    except FileNotFoundError:
        log_callback(f"Error: The file '{image_path}' was not found.")
        return None
    except Exception as e:
        log_callback(f"Error: Could not open image. Reason: {e}")
        return None

    source_image = source_image.convert("RGBA")
    log_callback("Image converted to RGBA.")

    target_dims = BANNER_DIMS if asset_type == 'banner' else BADGE_DIMS
    log_callback(f"Resizing image to {target_dims[0]}x{target_dims[1]}...")
    resized_image = source_image.resize(target_dims, Image.Resampling.LANCZOS)

    os.makedirs(output_dir, exist_ok=True)
    base_name = os.path.splitext(os.path.basename(image_path))[0]
    output_filename = f"{base_name}_{asset_type}.tga"
    output_path = os.path.join(output_dir, output_filename)

    try:
        resized_image.save(output_path, 'TGA')
        log_callback(f"\nSuccess! Your {asset_type} has been saved to:\n{os.path.abspath(output_path)}")
        return output_path
    except Exception as e:
        log_callback(f"Error: Failed to save Targa file. Reason: {e}")
        return None

# --- GUI Application Class ---

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Dawn of War Asset Creator")
        self.geometry("650x500")
        self.configure(bg="#f0f0f0")

        self.source_image_path = tk.StringVar()
        self.output_dir_path = tk.StringVar(value=os.path.join(os.getcwd(), "dow_assets_output"))
        self.asset_type = tk.StringVar(value="badge")
        self.preview_image = None

        self.create_widgets()

    def create_widgets(self):
        main_frame = tk.Frame(self, padx=15, pady=15, bg="#f0f0f0")
        main_frame.pack(fill=tk.BOTH, expand=True)

        file_frame = tk.LabelFrame(main_frame, text="1. Select Source Image", padx=10, pady=10, bg="#f0f0f0")
        file_frame.pack(fill=tk.X, pady=(0, 10))
        tk.Entry(file_frame, textvariable=self.source_image_path, state='readonly', width=60).pack(side=tk.LEFT, fill=tk.X, expand=True, ipady=4)
        tk.Button(file_frame, text="Browse...", command=self.select_source_image).pack(side=tk.LEFT, padx=(5, 0))

        preview_frame = tk.LabelFrame(main_frame, text="Image Preview", padx=10, pady=10, bg="#f0f0f0")
        preview_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        self.preview_label = tk.Label(preview_frame, bg="white", text="Select an image to see a preview")
        self.preview_label.pack(fill=tk.BOTH, expand=True)

        type_frame = tk.LabelFrame(main_frame, text="2. Asset Type", padx=10, pady=5, bg="#f0f0f0")
        type_frame.pack(fill=tk.X, pady=(0, 10))
        tk.Radiobutton(type_frame, text="Badge (64x64)", variable=self.asset_type, value="badge", bg="#f0f0f0").pack(anchor=tk.W)
        tk.Radiobutton(type_frame, text="Banner (64x96)", variable=self.asset_type, value="banner", bg="#f0f0f0").pack(anchor=tk.W)

        output_frame = tk.LabelFrame(main_frame, text="3. Select Output Folder", padx=10, pady=10, bg="#f0f0f0")
        output_frame.pack(fill=tk.X, pady=10)
        tk.Entry(output_frame, textvariable=self.output_dir_path, state='readonly', width=60).pack(side=tk.LEFT, fill=tk.X, expand=True, ipady=4)
        tk.Button(output_frame, text="Browse...", command=self.select_output_dir).pack(side=tk.LEFT, padx=(5, 0))

        tk.Button(main_frame, text="Create Asset", command=self.run_conversion, font=("Helvetica", 12, "bold"), bg="#4CAF50", fg="white", relief=tk.RAISED).pack(fill=tk.X, ipady=8, pady=5)

    def select_source_image(self):
        path = filedialog.askopenfilename(
            title="Select Image File",
            filetypes=[("Image Files", "*.png *.jpg *.jpeg *.bmp *.gif"), ("All files", "*.*")]
        )
        if path:
            self.source_image_path.set(path)
            self.update_preview(path)

    def update_preview(self, path):
        try:
            img = Image.open(path)
            img.thumbnail((self.preview_label.winfo_width(), self.preview_label.winfo_height()), Image.Resampling.LANCZOS)
            self.preview_image = ImageTk.PhotoImage(img)
            self.preview_label.config(image=self.preview_image, text="")
        except Exception as e:
            self.preview_label.config(image="", text=f"Could not preview image:\n{e}")

    def select_output_dir(self):
        path = filedialog.askdirectory(title="Select Output Folder")
        if path:
            self.output_dir_path.set(path)

    def run_conversion(self):
        if not self.source_image_path.get():
            messagebox.showerror("Error", "Please select a source image file.")
            return
        if not self.output_dir_path.get():
            messagebox.showerror("Error", "Please select an output folder.")
            return
        self.show_log_window()

    def show_log_window(self):
        log_window = tk.Toplevel(self)
        log_window.title("Processing...")
        log_window.geometry("500x300")

        log_text = tk.Text(log_window, wrap=tk.WORD, state='disabled', padx=10, pady=10)
        log_text.pack(fill=tk.BOTH, expand=True)

        def log_message(message):
            log_text.config(state='normal')
            log_text.insert(tk.END, message + "\n")
            log_text.config(state='disabled')
            log_text.see(tk.END)
            log_window.update_idletasks()

        def process():
            try:
                output_file = create_asset(
                    self.source_image_path.get(),
                    self.output_dir_path.get(),
                    self.asset_type.get(),
                    log_callback=log_message
                )
                if output_file:
                    log_window.title("Success!")
                    messagebox.showinfo("Success", f"Asset created successfully!\n\nFile saved at:\n{output_file}", parent=log_window)
                else:
                    log_window.title("Failed!")
                    messagebox.showerror("Error", "Asset creation failed. See log for details.", parent=log_window)
            except Exception:
                log_message("\n--- AN UNEXPECTED ERROR OCCURRED ---")
                log_message(traceback.format_exc())
                log_window.title("Critical Error!")
                messagebox.showerror("Critical Error", "An unexpected error occurred. Please see the log.", parent=log_window)

        self.after(100, process)

if __name__ == "__main__":
    app = App()
    app.mainloop()
Editor is loading...
Leave a Comment