| import tkinter as tk
|
| from tkinter import filedialog, messagebox, simpledialog
|
| from tkinterdnd2 import DND_FILES, TkinterDnD
|
| from PIL import Image, ImageDraw, ImageGrab, ImageTk
|
| import win32clipboard
|
| import win32con
|
| import io
|
| import os
|
| import winsound
|
| from datetime import datetime
|
| from colorsys import hsv_to_rgb
|
| import colorsys
|
| import random
|
| import ctypes
|
| import time
|
| user32 = ctypes.windll.user32
|
|
|
| class ImageDrawer(TkinterDnD.Tk):
|
| def __init__(self):
|
| super().__init__()
|
|
|
| self.default_save_folder = os.path.dirname(os.path.abspath(__file__)) + "/saved_image"
|
|
|
| self.refresh_time = 0.01
|
|
|
| self.points = 64
|
|
|
|
|
| self.hwnd = ctypes.windll.kernel32.GetConsoleWindow()
|
| if self.hwnd:
|
| ctypes.windll.user32.ShowWindow(self.hwnd, 0)
|
| print("ターミナルを最小化します。")
|
|
|
| window_width = 950
|
| window_height = 996
|
| self.img_width = self.img_height = self.resize_width = self.resize_height = 1024
|
| self.geometry(f"{window_width}x{window_height}+0+0")
|
| self.display_title()
|
| self.current_size = (window_width, window_height)
|
|
|
|
|
| self.canvas_frame = tk.Frame(self)
|
| self.canvas_frame.grid(row=0, column=0, padx=(10, 0),sticky="nsew")
|
|
|
| self.canvas = tk.Canvas(self.canvas_frame, bg="gray50", highlightthickness=0, bd=0)
|
| self.canvas.grid(row=0, column=0, sticky="nsew")
|
| self.canvas.bind("<B1-Motion>", self.paint)
|
| self.canvas.bind("<Button-1>", self.paint)
|
| self.canvas.bind("<Button-2>", self.toggle_eraser)
|
| self.canvas.bind("<Button-3>", self.Eyedropper)
|
| self.bind("<space>", self.Eyedropper)
|
|
|
| self.grid_rowconfigure(0, weight=1)
|
| self.grid_columnconfigure(0, weight=1)
|
|
|
| self.canvas_frame.grid_rowconfigure(0, weight=1)
|
| self.canvas_frame.grid_columnconfigure(0, weight=1)
|
|
|
| self.y_scrollbar = tk.Scrollbar(self.canvas_frame, orient=tk.VERTICAL, command=self.canvas.yview)
|
| self.y_scrollbar.grid(row=0, column=1, sticky="ns")
|
|
|
| self.x_scrollbar = tk.Scrollbar(self, orient=tk.HORIZONTAL, command=self.canvas.xview)
|
| self.x_scrollbar.grid(row=1, column=0, sticky="ew")
|
|
|
| self.canvas.configure(xscrollcommand=self.x_scrollbar.set, yscrollcommand=self.y_scrollbar.set)
|
|
|
| self.drop_target_register(DND_FILES)
|
| self.dnd_bind("<<Drop>>", self.on_drop)
|
|
|
| button_frame = tk.Frame(self, bg="gray66")
|
| button_frame.grid(row=2, column=0, columnspan=2, sticky="ew")
|
|
|
| new_image = tk.Button(button_frame, text="新規", command=lambda: self.display_size_input_window())
|
| new_image.pack(side=tk.LEFT, padx=5)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
| open_button = tk.Button(button_frame, text="開く", command=self.open_image)
|
| open_button.pack(side=tk.LEFT)
|
| open_button.bind("<Button-3>", self.get_clipboard_image)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
| save_image = tk.Button(button_frame, text="保存", command=lambda: self.save_image(None))
|
| save_image.pack(side=tk.LEFT, padx=(5,0))
|
| save_image.bind("<Button-3>", self.save_image)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
|
|
| self.brush_size = 5
|
| self.hue = 0
|
| self.saturation = 0
|
| self.brightness = 0
|
| self.color = self.precolor = "#000000"
|
| self.cursor = None
|
|
|
| self.brush_size_label = tk.Label(button_frame, text=self.brush_size, font=("Arial Black", 20, "bold"), width=3, bg="gray66", justify="right", anchor="e")
|
| self.brush_size_label.pack(side=tk.LEFT)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
|
|
| self.brush_canvas = tk.Canvas(button_frame, bg="white", highlightthickness=0, bd=0, width=120, height=40)
|
| self.brush_canvas.pack(side=tk.LEFT, pady=3)
|
| self.brush_canvas.bind("<Button-1>", self.select_blush_size)
|
| self.brush_canvas.bind("<B1-Motion>", self.select_blush_size)
|
| self.brush_canvas.bind("<Button-3>", self.toggle_eraser)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
|
|
| self.eraser_button = tk.Button(button_frame, text="消", command=lambda: self.toggle_eraser(), font=("メイリオ", 15, "bold"), bg="black", fg="white")
|
| self.eraser_button.pack(side=tk.LEFT, padx=(0,10))
|
| self.eraser_button.bind("<Button-3>", self.toggle_eraser)
|
| self.bind("<x>", self.toggle_eraser)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
|
|
| black_white_frame = tk.Frame(button_frame, bg="gray66")
|
| black_white_frame.pack(side=tk.LEFT)
|
| white_canvas = tk.Canvas(black_white_frame, highlightthickness=0, bd=0, width=20, height=20, bg="white")
|
| white_canvas.grid(row=0, column=0, padx=5)
|
| white_canvas.bind("<Button-1>", self.white)
|
| self.bind("<w>", self.white)
|
| black_canvas = tk.Canvas(black_white_frame, highlightthickness=0, bd=0, width=20, height=20, bg="black")
|
| black_canvas.grid(row=1, column=0, padx=5)
|
| black_canvas.bind("<Button-1>", self.black)
|
| self.bind("<b>", self.black)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
|
|
| self.grayscale_canvas = tk.Canvas(button_frame, highlightthickness=0, bg="black", bd=0, width=40, height=40)
|
| self.grayscale_canvas.pack(side=tk.LEFT,pady=3)
|
| self.grayscale_canvas.bind("<Button-1>", self.pick_grayscale)
|
| self.grayscale_canvas.bind("<B1-Motion>", self.pick_grayscale)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
| self.grayscale_canvas_init()
|
|
|
| self.palette_canvas = tk.Canvas(button_frame, highlightthickness=0, bd=0, width=360, height=40)
|
| self.palette_canvas.pack(side=tk.LEFT, padx=5, pady=3)
|
| self.palette_canvas.bind("<Button-1>", self.pick_palette_color)
|
| self.palette_canvas.bind("<B1-Motion>", self.pick_palette_color)
|
| self.palette_canvas.bind("<Button-3>", self.pick_palette_color)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
|
|
| self.nav_canvas = tk.Canvas(button_frame, bg="navy", highlightthickness=0, bd=0, width=40, height=40)
|
| self.nav_canvas.pack(side=tk.LEFT, pady=3)
|
| self.nav_canvas.bind("<Button-1>", self.on_drag)
|
| self.nav_canvas.bind("<B1-Motion>", self.on_drag)
|
| self.nav_canvas.bind("<Button-3>", self.toggle_resize_image)
|
| tk.Frame(button_frame).pack(side="left", expand=True)
|
|
|
| layer_frame = tk.Frame(button_frame, bg="gray66")
|
| layer_frame.pack(side=tk.RIGHT, padx=5)
|
| self.label_text = ["1", "2", "3", "背"]
|
| self.reverse_number = [3, 2, 1, 0]
|
| self.layer_label = []
|
| for i in range(4):
|
| label = tk.Label(layer_frame, text=self.label_text[i], fg="white", bg="green")
|
| label.grid(row=0, column=i)
|
| self.layer_label.append(label)
|
| label.bind("<Button-1>", lambda event, idx=i: self.select_drawing_layer(event, idx))
|
| label.bind("<Button-2>", lambda event, idx=i: self.unite_layer(event, idx))
|
| label.bind("<Button-3>", lambda event, idx=i: self.toggle_layer(event, idx))
|
| self.layer_status = [True, True, True, True]
|
| clipboard_button = tk.Button(layer_frame, text="Clipboard",command= lambda: self.copy_to_clipboard(None))
|
| clipboard_button.grid(row=1, column=0, columnspan=4)
|
| clipboard_button.bind("<Button-2>", self.copy_to_clipboard)
|
| clipboard_button.bind("<Button-3>", self.copy_to_clipboard)
|
|
|
| self.bind("<MouseWheel>", self.change_brush_size)
|
| self.bind("<a>", self.change_brush_size)
|
| self.bind("<z>", self.change_brush_size)
|
| self.bind("<ButtonRelease>", self.on_release)
|
| self.bind("<Configure>", lambda event: self.play_window_resize_event(event))
|
| self.protocol("WM_DELETE_WINDOW", self.on_close)
|
| self.image_path = None
|
| self.eraser_mode = False
|
| self.click_off = True
|
| self.last_paint_time = 0
|
| self.last_x, self.last_y = 0, 0
|
| self.cursor = None
|
| self.sizes = [(640, 1536), (768, 1344), (832, 1216), (896, 1152), (1024, 1024), (1152, 896), (1216, 832), (1344, 768), (1536, 640)]
|
| self.display_brush_canvas()
|
| self.draw_palette_canvas()
|
| self.init_palette_line()
|
| self.change_bgcolor_grayscale_canvas()
|
| self.view_rect = self.nav_canvas.create_rectangle(0, 0, 10, 10, outline="yellow", width=2)
|
| self.images = []
|
| self.drawing_layer = 3
|
| for i in range(4):
|
| self.images.append(Image.new("RGBA", (self.img_width, self.img_height), (0, 0, 0, 0)))
|
| self.images[0] = Image.new("RGBA", (self.img_width, self.img_height), "#ffffff")
|
| self.update_idletasks()
|
| self.resize_mode = True
|
| self.reset_images()
|
| self.update_view_rect()
|
| winsound.PlaySound("C:/Windows/Media/Alarm02.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
|
|
| def reset_images(self):
|
| self.drawing_layer = 3
|
| for i in range(4):
|
| if not i == 0:
|
| self.images[i] = (Image.new("RGBA", (self.img_width, self.img_height), (0, 0, 0, 0)))
|
| self.layer_status[i] = True
|
| self.layer_label[i].config(bg="green")
|
| self.layer_label[i].config(text= self.label_text[i], fg= "white")
|
| self.select_drawing_layer(None, 0)
|
|
|
| def display_title(self):
|
| self.title(f"I2I Paint 4Layer 【{self.img_width} x {self.img_height}】")
|
|
|
| def on_release(self, event):
|
| self.click_off = True
|
|
|
| def on_close(self):
|
| result = messagebox.askyesno("確認", "終了してウインドウを閉じますか?", parent=self)
|
| if result:
|
| self.destroy()
|
|
|
| def play_window_resize_event(self, event):
|
| if hasattr(self, 'resize_timer') and self.resize_timer:
|
| self.after_cancel(self.resize_timer)
|
| self.resize_timer = self.after(500, self.check_if_resized)
|
|
|
| def check_if_resized(self):
|
| new_size = (self.winfo_width(), self.winfo_height())
|
| if new_size != self.current_size:
|
| self.current_size = new_size
|
| self.display_image()
|
|
|
| def display_size_input_window(self):
|
| self.size_input_window = tk.Toplevel(self)
|
| self.size_input_window.title("画像サイズ選択")
|
| tk.Label(self.size_input_window, text="画像サイズを選択してください").pack()
|
| size_var = tk.IntVar(value=4)
|
| self.radio_buttons = []
|
| for index, size in enumerate(self.sizes):
|
| rb = tk.Radiobutton(self.size_input_window, text=f"{size[0]} x {size[1]}", variable=size_var, value=index)
|
| rb.pack(anchor="w")
|
| self.radio_buttons.append(rb)
|
| rb = tk.Radiobutton(self.size_input_window, text="キーボードから入力", variable=size_var, value=9)
|
| rb.pack(anchor="w")
|
| self.radio_buttons.append(rb)
|
| tk.Button(self.size_input_window, text="決定", command=lambda: self.new_image(size_var.get())).pack()
|
| parent_width = self.winfo_width()
|
| parent_height = self.winfo_height()
|
| parent_x = self.winfo_x()
|
| parent_y = self.winfo_y()
|
| self.size_input_window.update_idletasks()
|
|
|
| child_width = self.size_input_window.winfo_width()
|
| child_height = self.size_input_window.winfo_height()
|
|
|
| child_x = parent_x + (parent_width // 2) - (child_width // 2)
|
| child_y = parent_y + (parent_height // 2) - (child_height // 2)
|
| self.size_input_window.geometry(f"{child_width}x{child_height}+{child_x}+{child_y}")
|
|
|
| def new_image(self, selected_size):
|
| if hasattr(self, 'size_input_window') and self.size_input_window:
|
| self.size_input_window.destroy()
|
| if selected_size ==9:
|
| while True:
|
| input_str = simpledialog.askstring("新規画像サイズ", "幅と高さをスペースで区切って入力してください/n例: 「800 600」 (最大値は4096)")
|
| if not input_str:
|
| return
|
| try:
|
| width, height = map(int, input_str.split())
|
| if 4096 > width > 0 and 4096 > height > 0:
|
| self.img_width = width
|
| self.img_height = height
|
| break
|
| except ValueError:
|
| pass
|
| else:
|
| self.img_width = self.resize_width = self.sizes[selected_size][0]
|
| self.img_height = self.resize_height = self.sizes[selected_size][1]
|
| self.canvas.config(scrollregion=(0, 0, self.img_width, self.img_height))
|
| result = messagebox.askyesnocancel("背景色", f"新規画像:{self.img_width}x{self.img_height}/n新規画像を現在の色で塗りつぶしますか?\n(「いいえ」=白背景)", parent=self)
|
| if result is None:
|
| return
|
| elif result:
|
| background_color = self.color
|
| else:
|
| background_color = "#ffffff"
|
|
|
| self.images[0] = Image.new("RGBA", (self.img_width, self.img_height), background_color)
|
|
|
| draw = ImageDraw.Draw(self.images[0])
|
|
|
| draw.rectangle([0, 0, self.img_width, self.img_height], fill=background_color)
|
| self.reset_images()
|
|
|
| self.resize_mode = True
|
| self.display_image()
|
| self.display_title()
|
| winsound.PlaySound("C:/Windows/Media/chord.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| self.on_drag(None)
|
| result = messagebox.askyesno("ノイズ", f"新規画像:{self.img_width}x{self.img_height}/n背景画面にノイズを載せますか?", parent=self)
|
| if result:
|
| noise_level = simpledialog.askinteger("ノイズ濃度", "ノイズの濃さを入力してください。(%)", minvalue=0, maxvalue=100, initialvalue=20, parent=self)
|
| if noise_level:
|
| self.images[0] = self.add_noise_to_image(self.images[0], noise_level)
|
| self.display_image()
|
|
|
| def add_noise_to_image(self, image, noise_level):
|
|
|
| img = image.convert("RGBA")
|
| pixels = img.load()
|
| width, height = img.size
|
| for y in range(height):
|
| for x in range(width):
|
|
|
| if random.random() < (noise_level / 100.0):
|
| r = random.randint(0, 255)
|
| g = random.randint(0, 255)
|
| b = random.randint(0, 255)
|
| a = pixels[x, y][3]
|
| pixels[x, y] = (r, g, b, a)
|
| return img
|
|
|
| def on_drop(self, event):
|
| """ドラッグアンドドロップで画像を開く"""
|
| self.image_path = event.data.strip("{}")
|
| self.load_image(self.image_path)
|
|
|
| def open_image(self):
|
| """ダイアログから画像を開く"""
|
| file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.png;*.jpg;*.webp;*.gif;*.bmp")])
|
| if file_path:
|
| self.load_image(file_path)
|
|
|
| def load_image(self, file_path):
|
| self.image_path = file_path
|
| try:
|
| """画像を読み込んでキャンバスに表示"""
|
| self.images[0] = Image.open(file_path).convert("RGBA")
|
| self.img_width, self.img_height = self.images[0].size
|
| self.reset_images()
|
| self.resize_mode = True
|
| self.display_image()
|
| self.display_title()
|
| winsound.PlaySound("C:/Windows/Media/chimes.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| self.on_drag(None)
|
| except Exception as e:
|
| print(f"ファイルの読み込みに失敗しました: {e}")
|
|
|
| def save_image(self, event=None):
|
| """タイムスタンプ付きで画像をファイルに保存"""
|
| image_to_save = self.displayed_image
|
| if event:
|
| folder_path = self.default_save_folder
|
| try:
|
| if not os.path.exists(folder_path):
|
| os.mkdir(folder_path)
|
|
|
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| file_name = f"image_{timestamp}"
|
|
|
| file_path = os.path.join(folder_path, file_name + ".png").replace('\\', '/')
|
| while os.path.exists(file_path):
|
| file_name += "+"
|
| file_path = os.path.join(folder_path, file_name + ".png").replace('\\', '/')
|
|
|
| image_to_save.save(file_path, "PNG")
|
| print(f"画像を保存しました: {file_path}")
|
| messagebox.showinfo("確認", f"画像を保存しました:\n{file_path}", parent=self)
|
| except Exception as e:
|
| print(f"保存エラー: {e}\n{folder_path}")
|
| else:
|
| timestamp = time.strftime("%Y%m%d_%H%M%S")
|
| file_path = filedialog.asksaveasfilename(
|
| defaultextension=".png",
|
| filetypes=[("PNG 画像", "*.png"), ("JPEG 画像", "*.jpg"), ("BMP 画像", "*.bmp"), ("すべてのファイル", "*.*")],
|
| initialfile=f"image_{timestamp}"
|
| )
|
| if not file_path:
|
| return
|
|
|
| try:
|
| image_to_save.save(file_path)
|
| messagebox.showinfo("確認", f"画像を保存しました:/n{file_path}", parent=self)
|
| except Exception as e:
|
| print(f"保存エラー: {e}\n{file_path}")
|
|
|
| def toggle_resize_image(self, event=None):
|
| self.resize_mode = not self.resize_mode
|
| self.display_image()
|
| winsound.PlaySound("C:/Windows/Media/Windows Exclamation.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
|
|
| def on_drag(self, event):
|
| if self.resize_mode:
|
| return
|
| """ `nav_canvas` 上で矩形をドラッグして `canvas` をスクロール """
|
| scale_x = self.img_width / 39
|
| scale_y = self.img_height / 39
|
|
|
| if event:
|
| x = min(max(event.x, 0), 39)
|
| y = min(max(event.y, 0), 39)
|
| else:
|
| x = y = 0
|
| scroll_x = (x * scale_x) / self.img_width
|
| scroll_y = (y * scale_y) / self.img_height
|
| self.canvas.xview_moveto(scroll_x)
|
| self.canvas.yview_moveto(scroll_y)
|
|
|
| self.update_view_rect()
|
|
|
| def update_view_rect(self):
|
| self.canvas.update()
|
| """ `canvas` の表示範囲を `nav_canvas` に反映する """
|
| canvas_x1 = self.canvas.xview()[0] * self.img_width
|
| canvas_y1 = self.canvas.yview()[0] * self.img_height
|
| canvas_x2 = self.canvas.xview()[1] * self.img_width
|
| canvas_y2 = self.canvas.yview()[1] * self.img_height
|
|
|
| scale_x = 40 / self.img_width
|
| scale_y = 40 / self.img_height
|
|
|
| x1 = canvas_x1 * scale_x
|
| y1 = canvas_y1 * scale_y
|
| x2 = canvas_x2 * scale_x
|
| y2 = canvas_y2 * scale_y
|
|
|
| self.nav_canvas.coords(self.view_rect, x1, y1, x2, y2)
|
|
|
| def select_drawing_layer(self, event, idx):
|
| index = self.reverse_number[idx]
|
| for i in range(4):
|
| self.layer_label[i].config(text= self.label_text[i], fg= "white")
|
| self.drawing_layer = index
|
| self.layer_label[idx].config(text= "●", fg= "orange")
|
| self.layer_status[index] = True
|
| self.layer_label[idx].config(bg="green")
|
| winsound.PlaySound("C:/Windows/Media/Windows Notify Calendar.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| self.display_image()
|
|
|
| def toggle_layer(self, event, idx):
|
| index = self.reverse_number[idx]
|
| self.layer_status[index] = not self.layer_status[index]
|
| label_color = ["black", "green"]
|
| self.layer_label[idx].config(bg=label_color[self.layer_status[index]])
|
| winsound.PlaySound("C:/Windows/Media/chord.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| self.display_image()
|
|
|
| def unite_layer(self, event, idx):
|
| index = self.reverse_number[idx]
|
| if index == 0:
|
| return
|
| result = messagebox.askyesno("レイヤー統合", f"レイヤー {idx + 1} を背景レイヤーに統合します。\nよろしいですか?", parent=self)
|
| if result:
|
| self.images[0] = Image.alpha_composite(self.images[0], self.images[index])
|
| self.images[index] = Image.new("RGBA", (self.img_width, self.img_height), (0, 0, 0, 0))
|
| self.display_image()
|
|
|
| def calculate_basic_value(self):
|
| self.canvas.update()
|
| self.frm_width = self.canvas.winfo_width()
|
| self.frm_height = self.canvas.winfo_height()
|
| self.adjust_x = self.adjust_y = 0
|
| if self.img_width <= self.frm_width:
|
| self.adjust_x = int((self.frm_width - self.img_width) / 2)
|
| if self.img_height <= self.frm_height:
|
| self.adjust_y = int((self.frm_height - self.img_height) / 2)
|
| self.img_aspect_ratio = self.img_width / max(self.img_height, 1)
|
| self.frame_aspect_ratio = self.frm_width / max(self.frm_height, 1)
|
| if self.img_aspect_ratio > self.frame_aspect_ratio:
|
| self.resize_width = self.frm_width
|
| self.resize_height = int(self.frm_width / self.img_aspect_ratio)
|
| self.dx, self.dy = 0, (self.frm_height - self.resize_height) / 2
|
| else:
|
| self.resize_height = self.frm_height
|
| self.resize_width = int(self.frm_height * self.img_aspect_ratio)
|
| self.dx, self.dy = (self.frm_width - self.resize_width) / 2, 0
|
| self.resize_width = max(self.resize_width, 1)
|
| self.resize_height = max(self.resize_height, 1)
|
| self.ratio = self.img_width / max(self.resize_width, 1)
|
| self.xplot = self.frm_width // 2
|
| self.yplot = self.frm_height // 2
|
|
|
| def overlap_layer(self):
|
| self.displayed_image = Image.new("RGBA", (self.img_width, self.img_height), (127, 127, 127, 255))
|
| for i in range(4):
|
| if self.layer_status[i]:
|
| self.displayed_image = Image.alpha_composite(self.displayed_image, self.images[i])
|
|
|
| def display_image(self):
|
| self.calculate_basic_value()
|
| self.overlap_layer()
|
| self.canvas.delete("all")
|
| if self.resize_mode:
|
| resized_image = self.displayed_image.resize((self.resize_width, self.resize_height), Image.LANCZOS)
|
| self.photo_image = ImageTk.PhotoImage(resized_image)
|
| self.canvas.create_image(self.xplot, self.yplot, anchor=tk.CENTER, image=self.photo_image)
|
| self.canvas.image = self.photo_image
|
| self.canvas.config(scrollregion=(0, 0, self.frm_width, self.frm_height))
|
| self.nav_canvas.config(bg="yellow")
|
| else:
|
| self.photo_image = ImageTk.PhotoImage(self.displayed_image)
|
| self.canvas.create_image(self.adjust_x, self.adjust_y, anchor=tk.NW, image=self.photo_image)
|
| self.canvas.image = self.photo_image
|
| self.canvas.config(scrollregion=(0, 0, self.img_width, self.img_height))
|
| self.nav_canvas.config(bg="navy")
|
| self.on_drag(None)
|
|
|
| def display_brush_canvas(self):
|
| if self.saturation < 0.1 and self.brightness > 0.9:
|
| outcolor = "black"
|
| else:
|
| outcolor = self.color
|
| self.brush_canvas.delete("all")
|
| x1, y1 = (60 - self.brush_size), (20 - self.brush_size)
|
| x2, y2 = (60 + self.brush_size), (20 + self.brush_size)
|
| self.brush_canvas.create_oval(x1, y1, x2, y2, fill=self.color, outline=outcolor)
|
| self.brush_size_label.config(fg=self.color)
|
|
|
| def display_grayscale_cursor(self):
|
| self.grayscale_canvas.delete(self.cursor)
|
| true_hue = self.hue * 360
|
| inverse_hue = int(true_hue + 180) % 360
|
| r, g, b = hsv_to_rgb(inverse_hue / 360, 1, 1)
|
| fill_color = f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"
|
| self.cursor = self.grayscale_canvas.create_text(self.saturation * 39, 39 - (self.brightness) * 39, text="◎", fill=fill_color)
|
| self.display_brush_canvas()
|
|
|
| def grayscale_canvas_init(self):
|
| """ HUEの背景とアルファグラデーションを適用 """
|
|
|
| white = Image.new("RGBA", (40, 40), (0, 0, 0, 0))
|
| draw_white = ImageDraw.Draw(white)
|
|
|
| for x in range(40):
|
| alpha = int((1 - (x / 39)) * 255)
|
| for y in range(40):
|
| draw_white.point((x, y), fill=(255, 255, 255, alpha))
|
|
|
| black = Image.new("RGBA", (40, 40), (0, 0, 0, 0))
|
| draw_black = ImageDraw.Draw(black)
|
| for y in range(40):
|
| alpha = int(y / 39 * 255)
|
| for x in range(40):
|
| draw_black.point((x, y), fill=(0, 0, 0, alpha))
|
|
|
| self.filter_image = Image.alpha_composite(white, black)
|
| self.filter_tk = ImageTk.PhotoImage(self.filter_image)
|
|
|
| self.grayscale_canvas.create_image(0, 0, anchor=tk.NW, image=self.filter_tk)
|
|
|
| def init_palette_line(self):
|
| """ パレット上のHUEのラインを初期化 """
|
| white_line = Image.new("RGBA", (1, 40), (0, 0, 0, 0))
|
| draw_line = ImageDraw.Draw(white_line)
|
| draw_line.line((0, 0, 0, 39), fill=(0, 0, 0, 255), width=1)
|
| line_tk = ImageTk.PhotoImage(white_line)
|
| self.hue_line_img = line_tk
|
| self.hue_line = self.palette_canvas.create_image(0, 0, anchor=tk.NW, image=self.hue_line_img)
|
|
|
| def change_bgcolor_grayscale_canvas(self):
|
| """ 背景色をHUEで変更し、グラデーションと合成 """
|
| r, g, b = hsv_to_rgb(self.hue, 1, 1)
|
| color = f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"
|
| self.grayscale_canvas.config(bg=color)
|
| self.display_grayscale_cursor()
|
| hue_x = int(self.hue * 359)
|
| self.palette_canvas.coords(self.hue_line, hue_x, 0)
|
|
|
| def draw_palette_canvas(self):
|
| """HSVの色相 (H) と彩度 (S) を変化させたグラデーションを描画"""
|
| for x in range(360):
|
| hue = x / 359
|
| for y in range(40):
|
| if y < 20:
|
| saturation = y / 19
|
| brightness = 1
|
| else:
|
| saturation = 1
|
| brightness = 1 - 0.8 * ((y-20) / 19)
|
| r, g, b = hsv_to_rgb(hue, saturation, brightness)
|
| color = f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"
|
| self.palette_canvas.create_rectangle(x, y, x, y, outline=color, fill=color)
|
|
|
| def hsv_to_hex_color(self, hue, saturation, brightness):
|
| r, g, b = hsv_to_rgb(hue, saturation, brightness)
|
| self.color = f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"
|
|
|
| def black(self, event):
|
| self.brightness = 0
|
| self.hsv_to_hex_color(self.hue, self.saturation, self.brightness)
|
| self.black_and_white()
|
|
|
| def white(self, event):
|
| self.saturation = 0
|
| self.brightness = 1
|
| self.hsv_to_hex_color(self.hue, self.saturation, self.brightness)
|
| self.black_and_white()
|
|
|
| def black_and_white(self):
|
| winsound.PlaySound("C:/Windows/Media/chord.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| self.display_grayscale_cursor()
|
| if self.eraser_mode:
|
| self.eraser_mode = False
|
| self.eraser_button.config(bg="black")
|
| self.brush_canvas.config(bg="white")
|
|
|
| def Eyedropper(self, event):
|
| """右クリックでスポイト (カーソル下の色を取得)"""
|
| x, y = self.winfo_rootx() + event.x, self.winfo_rooty() + event.y
|
| img = ImageGrab.grab(bbox=(x, y, x + 1, y + 1))
|
| color_rgb = img.getpixel((0, 0))
|
|
|
| r, g, b = [x / 255.0 for x in color_rgb]
|
|
|
| self.hue, self.saturation, self.brightness = colorsys.rgb_to_hsv(r, g, b)
|
| self.hsv_to_hex_color(self.hue, self.saturation, self.brightness)
|
| self.change_bgcolor_grayscale_canvas()
|
| winsound.PlaySound("C:/Windows/Media/chord.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| if self.eraser_mode:
|
| self.eraser_mode = False
|
| self.eraser_button.config(bg="black")
|
| self.brush_canvas.config(bg="white")
|
|
|
| def pick_grayscale(self, event):
|
| """クリックした位置の色を取得し、ラベルに表示"""
|
| x, y = event.x, event.y
|
| self.saturation = min(max(x / 39, 0), 1)
|
| self.brightness = min(max(1 - (y / 39), 0), 1)
|
| self.hsv_to_hex_color(self.hue, self.saturation, self.brightness)
|
| self.display_grayscale_cursor()
|
| winsound.PlaySound("C:/Windows/Media/Windows Information Bar.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| if self.eraser_mode:
|
| self.eraser_mode = False
|
| self.eraser_button.config(bg="black")
|
| self.brush_canvas.config(bg="white")
|
|
|
| def pick_palette_color(self, event):
|
| """クリックした位置の色を取得し、ラベルに表示"""
|
| x, y = event.x, event.y
|
| self.hue = min(max(x / 359, 0), 1)
|
| if event.num == 1:
|
| if y < 20:
|
| self.saturation = min(max(y / 19, 0), 1)
|
| self.brightness = 1
|
| else:
|
| y -= 20
|
| self.saturation = 1
|
| self.brightness = min(max(1 - (0.8 * y / 19), 0), 1)
|
| else:
|
| self.saturation = 1.0
|
| self.brightness = 1.0
|
| self.hsv_to_hex_color(self.hue, self.saturation, self.brightness)
|
| self.change_bgcolor_grayscale_canvas()
|
| winsound.PlaySound("C:/Windows/Media/Windows Information Bar.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| if self.eraser_mode:
|
| self.eraser_mode = False
|
| self.eraser_button.config(bg="black")
|
| self.brush_canvas.config(bg="white")
|
|
|
| def adjust_color_brightness(self, event):
|
| """マウスホイールで self.color の明度 (V) を調整"""
|
| if self.eraser_mode:
|
| return
|
| old_color = self.color
|
| delta = 0.05
|
| if event.delta > 0:
|
| self.brightness = min(self.brightness + delta, 1)
|
| else:
|
| self.brightness = max(self.brightness - delta, 0)
|
| self.hsv_to_hex_color(self.hue, self.saturation, self.brightness)
|
| if not self.color == old_color:
|
| self.display_grayscale_cursor()
|
| winsound.PlaySound("C:/Windows/Media/Windows Information Bar.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
|
|
| def change_brush_size(self, event):
|
| widget = self.winfo_containing(event.x_root, event.y_root)
|
| if widget == self.canvas:
|
| if event.keysym == "z":
|
| self.brush_size = min(max(1, self.brush_size - 10), 512)
|
| elif event.keysym == "a":
|
| self.brush_size = min(max(1, self.brush_size + 10), 512)
|
| else:
|
| self.brush_size = min(max(1, self.brush_size + (1 if event.delta > 0 else -1)), 512)
|
| self.brush_size_label.config(text=self.brush_size)
|
| winsound.PlaySound("C:/Windows/Media/Windows Information Bar.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| self.display_brush_canvas()
|
| else:
|
| self.adjust_color_brightness(event)
|
|
|
| def select_blush_size(self, event):
|
| self.brush_size = abs(event.x - 60)
|
| self.brush_size_label.config(text=self.brush_size)
|
| winsound.PlaySound("C:/Windows/Media/Windows Information Bar.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| self.display_brush_canvas()
|
|
|
| def toggle_eraser(self, event=None):
|
| """消しゴムモードの切り替え"""
|
| self.eraser_mode = not self.eraser_mode
|
| if self.eraser_mode:
|
| self.precolor = self.color
|
| self.color = "white"
|
| self.eraser_button.config(bg="red")
|
| self.brush_canvas.config(bg="black")
|
| winsound.PlaySound("C:/Windows/Media/Windows Exclamation.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| else:
|
| self.color = self.precolor
|
| self.eraser_button.config( bg="black")
|
| self.brush_canvas.config(bg="white")
|
| winsound.PlaySound("C:/Windows/Media/chord.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| self.display_brush_canvas()
|
|
|
| def paint(self, event):
|
| if self.resize_mode:
|
| x = self.canvas.canvasx(event.x) - self.dx
|
| y = self.canvas.canvasy(event.y) - self.dy
|
|
|
| x_original = int(x * self.ratio)
|
| y_original = int(y * self.ratio)
|
|
|
| x1, y1 = x_original - self.brush_size, y_original - self.brush_size
|
| x2, y2 = x_original + self.brush_size, y_original + self.brush_size
|
| x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
|
| current_time = time.time()
|
| time_difference = current_time - self.last_paint_time
|
| if not self.click_off:
|
| delta_x, delta_y = x_original - self.last_x, y_original - self.last_y
|
| for i in range(0, self.points):
|
| xx = self.last_x + (delta_x * i / self.points)
|
| yy = self.last_y + (delta_y * i / self.points)
|
| x1, y1 = (xx - self.brush_size), (yy - self.brush_size)
|
| x2, y2 = (xx + self.brush_size), (yy + self.brush_size)
|
| self.draw_point(x1, y1, x2, y2,)
|
| self.draw_point(x1, y1, x2, y2)
|
| if time_difference > self.refresh_time:
|
| self.overlap_layer()
|
| resized_image = self.displayed_image.resize((self.resize_width, self.resize_height), Image.LANCZOS)
|
| self.photo_image = ImageTk.PhotoImage(resized_image)
|
| self.canvas.create_image(self.xplot, self.yplot, anchor=tk.CENTER, image=self.photo_image)
|
| self.last_paint_time = current_time
|
| self.click_off = False
|
| self.last_x, self.last_y = x_original, y_original
|
| else:
|
| """描画処理 (スクロール対応)"""
|
| x = self.canvas.canvasx(event.x) - self.adjust_x
|
| y = self.canvas.canvasy(event.y) - self.adjust_y
|
| x1, y1 = (x - self.brush_size), (y - self.brush_size)
|
| x2, y2 = (x + self.brush_size), (y + self.brush_size)
|
| x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
|
| current_time = time.time()
|
| time_difference = current_time - self.last_paint_time
|
| if not self.click_off:
|
| delta_x, delta_y = x - self.last_x, y - self.last_y
|
| for i in range(0, self.points):
|
| xx = self.last_x + (delta_x * i / self.points)
|
| yy = self.last_y + (delta_y * i / self.points)
|
| x1, y1 = (xx - self.brush_size), (yy - self.brush_size)
|
| x2, y2 = (xx + self.brush_size), (yy + self.brush_size)
|
| self.draw_point(x1, y1, x2, y2,)
|
| self.draw_point(x1, y1, x2, y2)
|
| if time_difference > self.refresh_time:
|
| self.overlap_layer()
|
| self.photo_image = ImageTk.PhotoImage(self.displayed_image)
|
| self.canvas.create_image(self.adjust_x, self.adjust_y, anchor=tk.NW, image=self.photo_image)
|
| self.last_paint_time = current_time
|
|
|
| self.click_off = False
|
| self.last_x, self.last_y = x, y
|
|
|
| def draw_point(self, x1, y1, x2, y2):
|
| draw =ImageDraw.Draw(self.images[self.drawing_layer])
|
| if self.eraser_mode:
|
| draw.ellipse([x1, y1, x2, y2], fill=(0, 0, 0, 0))
|
| else:
|
| draw.ellipse([x1, y1, x2, y2], fill=self.color)
|
|
|
| def copy_to_clipboard(self, event):
|
| """キャンバス上に描かれた画像をクリップボードにコピー"""
|
| if event is None:
|
| clipboard_image = self.displayed_image
|
| else:
|
| mask_image = Image.new("RGBA", (self.img_width, self.img_height), (0, 0, 0, 0))
|
| if event.num == 2:
|
| for i in range(1, 4):
|
| if self.layer_status[i]:
|
| mask_image = Image.alpha_composite(mask_image, self.images[i])
|
| else:
|
| mask_image = Image.alpha_composite(mask_image, self.images[self.drawing_layer])
|
| clipboard_image = mask_image.copy()
|
| pixels = clipboard_image.load()
|
|
|
| width, height = clipboard_image.size
|
|
|
| for y in range(height):
|
| for x in range(width):
|
| r, g, b, a = pixels[x, y]
|
| if a > 0:
|
| pixels[x, y] = (255, 255, 255, a)
|
| else:
|
| pixels[x, y] = (0, 0, 0, a)
|
| output = io.BytesIO()
|
| clipboard_image.convert("RGB").save(output, format="BMP")
|
| data = output.getvalue()[14:]
|
| try:
|
| win32clipboard.OpenClipboard()
|
| win32clipboard.EmptyClipboard()
|
| win32clipboard.SetClipboardData(win32con.CF_DIB, data)
|
| winsound.PlaySound("C:/Windows/Media/chimes.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
| except Exception as e:
|
| print(f"画像のコピーに失敗: {e}")
|
| finally:
|
| win32clipboard.CloseClipboard()
|
|
|
| def get_clipboard_image(self, event=None):
|
| win32clipboard.OpenClipboard()
|
| try:
|
| if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB):
|
| data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)
|
| else:
|
| print("クリップボードに画像がありません。")
|
| return None
|
| finally:
|
| win32clipboard.CloseClipboard()
|
|
|
| bmp_data = io.BytesIO()
|
| bmp_data.write(b'BM')
|
| bmp_data.write((len(data) + 14).to_bytes(4, 'little'))
|
| bmp_data.write(b'\x00\x00\x00\x00')
|
| bmp_data.write((14 + 40).to_bytes(4, 'little'))
|
| bmp_data.write(data)
|
| bmp_data.seek(0)
|
|
|
| image = Image.open(bmp_data)
|
|
|
| self.images[0] = image.convert("RGBA")
|
| self.img_width, self.img_height = self.images[0].size
|
| self.reset_images()
|
|
|
| self.resize_mode = True
|
| self.display_image()
|
| self.display_title()
|
|
|
| winsound.PlaySound("C:/Windows/Media/chimes.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
|
|
|
| self.on_drag(None)
|
|
|
|
|
| if __name__ == "__main__":
|
| app = ImageDrawer()
|
| app.mainloop()
|
|
|