File size: 42,723 Bytes
940b5d5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 |
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()
|