I2I-Paint / I2I-Paint.py
Gazou-Seiri-Bu's picture
Upload I2I-Paint.py
940b5d5 verified
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"
#画面の描画間隔: 50FPS => 0.02, 100FPS => 0.01, 125FPS => 0.008
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) # 右クリックでスポイト
# `canvas_frame` をウィンドウ全体に広げる
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
# `canvas_frame` 内の `canvas` も拡張
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)
# DND 設定
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)
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)
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)
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.layer_label = tk.Label(layer_frame, text="両", fg="white", bg="blue")
self.layer_label.grid(row=0, column=0)
layer_button = tk.Button(layer_frame, command = self.rotate_layer, text="Layer")
layer_button.grid(row=0, column=1)
layer_button.bind("<Button-3>", self.unite_layer)
clipboard_button = tk.Button(layer_frame, text="Clipboard",command= lambda: self.copy_to_clipboard(None))
clipboard_button.grid(row=1, column=0, columnspan=2)
clipboard_button.bind("<Button-3>", self.copy_to_clipboard)
self.bind("<MouseWheel>", 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.layer_mode = 0
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.adjust_x, self.adjust_y = 0, 0
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.background_image = Image.new("RGBA", (self.img_width, self.img_height), "#ffffff")
self.drawn_image = Image.new("RGBA", (self.img_width, self.img_height), (0, 0, 0, 0))
self.update_idletasks()
self.resize_mode = True
self.display_image()
self.update_view_rect()
winsound.PlaySound("C:/Windows/Media/Alarm02.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
def display_title(self):
self.title(f"I2I Paint 【{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(False) # サイズが確定したときに一度だけ呼び出す
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) # デフォルトを中央の 1024x1024 に設定
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"
# 新しい画像を作成(RGBAモードで、背景色は透明)
self.background_image = Image.new("RGBA", (self.img_width, self.img_height), background_color)
# 塗りつぶし処理
draw = ImageDraw.Draw(self.background_image)
# 現在の色で全体を塗りつぶす
draw.rectangle([0, 0, self.img_width, self.img_height], fill=background_color)
# 必要に応じて描画後の画像をキャンバスに再表示する処理を追加
self.drawn_image = Image.new("RGBA", (self.img_width, self.img_height), (255, 255, 255, 0))
self.layer_mode = 0
self.layer_label.config(text="両", bg="blue")
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.background_image = self.add_noise_to_image(self.background_image, noise_level)
self.display_image()
def add_noise_to_image(self, image, noise_level):
# 画像をRGBAモードで開く(透明度も考慮)
img = image.convert("RGBA")
pixels = img.load() # ピクセルデータを取得
width, height = img.size
for y in range(height):
for x in range(width):
# ノイズの強さに応じてピクセルのRGB値をランダムに変化させる
if random.random() < (noise_level / 100.0): # noise_level%の確率でノイズ
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.background_image = Image.open(file_path).convert("RGBA")
self.img_width, self.img_height = self.background_image.size
self.drawn_image = Image.new("RGBA", (self.img_width, self.img_height), (0, 0, 0, 0))
self.layer_mode = 0
self.layer_label.config(text="両", bg="blue")
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.original_image
if event: # `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: # `event` がない場合(手動保存)
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()
def on_drag(self, event):
if self.resize_mode:
winsound.PlaySound("C:/Windows/Media/Windows Exclamation.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
return
""" `nav_canvas` 上で矩形をドラッグして `canvas` をスクロール """
scale_x = self.img_width / 39
scale_y = self.img_height / 39
# `nav_canvas` の範囲内に収める
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)
# `view_rect` を更新
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
# nav_canvas 上の矩形の位置を計算
x1 = canvas_x1 * scale_x
y1 = canvas_y1 * scale_y
x2 = canvas_x2 * scale_x
y2 = canvas_y2 * scale_y
# nav_canvas 上のビュー範囲を更新
self.nav_canvas.coords(self.view_rect, x1, y1, x2, y2)
def rotate_layer(self):
self.layer_mode = (self.layer_mode + 1) % 3
layer_mode_name = ["両", "前", "後"]
layer_mode_color = ["blue2", "green4", "orange3"]
self.layer_label.config(text= layer_mode_name[self.layer_mode], bg=layer_mode_color[self.layer_mode])
# winsound.PlaySound("C:/Windows/Media/chord.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
self.display_image()
def unite_layer(self, event):
result = messagebox.askyesno("レイヤー統合", "二つのレイヤーと統合して後レイヤーにします。\nよろしいですか?", parent=self)
if result:
self.background_image = Image.alpha_composite(self.background_image, self.drawn_image)
self.drawn_image = 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 display_image(self, sound = True):
self.calculate_basic_value()
if self.layer_mode == 0:
self.original_image = Image.alpha_composite(self.background_image, self.drawn_image)
elif self.layer_mode == 1:
self.original_image =self.drawn_image
else:
self.original_image = self.background_image
self.canvas.delete("all")
if self.resize_mode:
resized_image = self.original_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 # GC対策
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.original_image)
self.canvas.create_image(self.adjust_x, self.adjust_y, anchor=tk.NW, image=self.photo_image)
self.canvas.image = self.photo_image # GC対策
self.canvas.config(scrollregion=(0, 0, self.img_width, self.img_height))
self.nav_canvas.config(bg="navy")
self.on_drag(None)
if sound:
winsound.PlaySound("C:/Windows/Media/chord.wav", winsound.SND_FILENAME | winsound.SND_ASYNC)
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 # 0.0~1.0 を 0~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の背景とアルファグラデーションを適用 """
# RGBA画像を作成(背景は完全に透明)
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) # 0 (透明) ~ 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) # 0 (透明) ~ 255 (不透明)
for x in range(40):
draw_black.point((x, y), fill=(0, 0, 0, alpha))
# 画像の合成(Imageオブジェクトを使用)
self.filter_image = Image.alpha_composite(white, black)
self.filter_tk = ImageTk.PhotoImage(self.filter_image)
# Canvasに適用
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 # GC対策
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) # HUEをRGBに変換
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) # HUEを0-39の範囲でスケール変換
self.palette_canvas.coords(self.hue_line, hue_x, 0)
def draw_palette_canvas(self):
"""HSVの色相 (H) と彩度 (S) を変化させたグラデーションを描画"""
for x in range(360): # x = 0 から x = 358 まで
hue = x / 359 # 色相を 0.0 ~ 1.0 に正規化
for y in range(40):
if y < 20:
saturation = y / 19 # 彩度 (0.0 ~ 1.0)
brightness = 1
else:
saturation = 1
brightness = 1 - 0.8 * ((y-20) / 19) # 明度 (0.0 ~ 1.0)
r, g, b = hsv_to_rgb(hue, saturation, brightness) # 明度は常に1.0(最大)
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) # 明度は常に1.0(最大)
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))
# RGBを0-1の範囲に変換
r, g, b = [x / 255.0 for x in color_rgb]
# RGBをHSVに変換
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) # 色相 (0.0 ~ 1.0)
if event.num == 1:
if y < 20:
self.saturation = min(max(y / 19, 0), 1) # 彩度 (0.0 ~ 1.0)
self.brightness = 1
else:
y -= 20
self.saturation = 1
self.brightness = min(max(1 - (0.8 * y / 19), 0), 1) # 明度 (0.0 ~ 1.0)
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 # 1回のスクロールで増減する値
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:
self.brush_size = max(1, self.brush_size + (1 if event.delta > 0 else -1))
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:
if self.layer_mode == 0:
self.original_image = Image.alpha_composite(self.background_image, self.drawn_image)
elif self.layer_mode == 1:
self.original_image = self.drawn_image
else:
self.original_image = self.background_image
resized_image = self.original_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:
if self.layer_mode == 0:
self.original_image = Image.alpha_composite(self.background_image, self.drawn_image)
elif self.layer_mode == 1:
self.original_image = self.drawn_image
else:
self.original_image = self.background_image
self.photo_image = ImageTk.PhotoImage(self.original_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):
if self.layer_mode == 2:
draw =ImageDraw.Draw(self.background_image)
else:
draw = ImageDraw.Draw(self.drawn_image)
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:
clipboard_image = self.drawn_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: # アルファ値が0ではない部分
pixels[x, y] = (255, 255, 255, a)
else:
pixels[x, y] = (0, 0, 0, a)
else:
clipboard_image = self.original_image
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 のヘッダーを適切に追加して PIL 画像に変換
bmp_data = io.BytesIO()
bmp_data.write(b'BM') # BMP シグネチャ
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) # DIB データ
bmp_data.seek(0) # 先頭に戻す
# PIL 画像として開く
image = Image.open(bmp_data)
# 取得した画像を `self.background_image` に設定
self.background_image = image.convert("RGBA") # ここで RGBA に変換
self.img_width, self.img_height = self.background_image.size
self.drawn_image = Image.new("RGBA", (self.img_width, self.img_height), (0, 0, 0, 0))
# UI の更新
self.layer_mode = 0
self.layer_label.config(text="両", bg="blue")
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()