Repository navigation
Expand file tree
/
Copy pathctf_binary_qrcode_plotter.py
More file actions
600 lines (513 loc) · 23.3 KB
/
Copy pathctf_binary_qrcode_plotter.py
File metadata and controls
600 lines (513 loc) · 23.3 KB
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
# -*- coding: utf-8 -*-
"""
二进制二维码与坐标绘图工具
===========================
统一GUI工具,支持两种模式:
1. 二进制模式:将二进制字符串生成为二维码图案
2. 坐标模式:从坐标文件读取点坐标并绘制散点图
依赖:tkinter, PIL, math, re, ast
"""
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from PIL import Image, ImageDraw, ImageTk
import math
import re
from ast import literal_eval
class UnifiedTool:
"""统一工具主类"""
def __init__(self, root):
self.root = root
self.root.title("二进制二维码与坐标绘图工具")
self.root.geometry("800x750")
self.root.resizable(False, False)
# ======== 二进制模式参数 ========
self.binary_string = "" # 原始二进制字符串
self.binary_matrix = [] # 二维矩阵 0/1
self.cell_size = 8 # 每个格子的像素大小
self.binary_image_raw = None # 原始全尺寸图像
self.binary_preview = None # 缩放后的预览图像
# ======== 坐标模式参数 ========
self.coords = [] # 坐标点列表 [(x,y), ...]
self.coord_file_path = "Paint&Scan.txt" # 默认坐标文件路径
self.coord_canvas_size = 800 # 画布大小
self.coord_margin = 20 # 边距
self.coord_point_radius = 2 # 点半径
self.coord_flip_y = True # 是否翻转Y轴
self.coord_image_raw = None # 原始全尺寸图像
self.coord_preview = None # 缩放后的预览图像
self.coord_min_x = 0 # X轴最小值
self.coord_max_x = 0 # X轴最大值
self.coord_min_y = 0 # Y轴最小值
self.coord_max_y = 0 # Y轴最大值
self.coord_loaded_count = 0 # 已加载坐标数量
# ======== 当前显示 ========
self.current_photo = None # 当前显示的 PhotoImage
self.create_widgets()
# 启动时显示二进制模式预览(示例数据)
self.binary_generate()
# ============================================================
# 界面构建
# ============================================================
def create_widgets(self):
"""创建主界面布局"""
# 主框架
main_frame = tk.Frame(self.root, padx=10, pady=10)
main_frame.pack(fill=tk.BOTH, expand=True)
# ----- 左侧:Notebook选项卡区域 -----
left_frame = tk.Frame(main_frame)
left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
self.notebook = ttk.Notebook(left_frame)
self.notebook.pack(fill=tk.BOTH, expand=True)
self.notebook.bind("<<NotebookTabChanged>>", self.on_tab_change)
# 选项卡1:二进制模式
self.tab_binary = ttk.Frame(self.notebook)
self.notebook.add(self.tab_binary, text="二进制模式")
self.create_binary_tab()
# 选项卡2:坐标模式
self.tab_coord = ttk.Frame(self.notebook)
self.notebook.add(self.tab_coord, text="坐标模式")
self.create_coord_tab()
# ----- 右侧:统一预览区域 -----
right_frame = tk.Frame(main_frame, relief=tk.SUNKEN, bd=2, bg="white", width=400)
right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
right_frame.pack_propagate(False) # 固定宽度
self.preview_label = tk.Label(right_frame, bg="white", text="预览区域", font=("Arial", 12), fg="gray")
self.preview_label.pack(expand=True)
# ----- 底部状态栏 -----
self.status_label = tk.Label(
self.root, text="就绪", fg="green", font=("Arial", 9),
bd=1, relief=tk.SUNKEN, anchor=tk.W, padx=10
)
self.status_label.pack(fill=tk.X, side=tk.BOTTOM)
# ---------- 二进制模式选项卡 ----------
def create_binary_tab(self):
"""创建二进制模式的控制界面"""
frame = self.tab_binary
frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# 输入标签
tk.Label(frame, text="二进制字符串 (仅包含0和1):",
font=("微软雅黑", 10, "bold")).pack(anchor="w")
# 文本输入框
self.text_binary = tk.Text(frame, height=8, wrap=tk.WORD, font=("Consolas", 10))
self.text_binary.pack(fill=tk.BOTH, expand=True, pady=5)
self.text_binary.insert("1.0", "10110011100011110000111100001111") # 示例数据
# 按钮行
btn_frame = tk.Frame(frame)
btn_frame.pack(fill=tk.X, pady=5)
tk.Button(btn_frame, text="从文件加载", command=self.binary_load_file,
width=12).pack(side=tk.LEFT, padx=2)
tk.Button(btn_frame, text="生成二维码", command=self.binary_generate,
width=12).pack(side=tk.LEFT, padx=2)
tk.Button(btn_frame, text="保存图片", command=self.binary_save,
width=12).pack(side=tk.LEFT, padx=2)
tk.Button(btn_frame, text="清空", command=self.binary_clear,
width=12).pack(side=tk.LEFT, padx=2)
# 格子大小调节滑块
size_frame = tk.Frame(frame)
size_frame.pack(fill=tk.X, pady=5)
tk.Label(size_frame, text="格子大小 (像素):").pack(side=tk.LEFT)
self.size_scale = tk.Scale(
size_frame, from_=4, to=32, orient=tk.HORIZONTAL,
command=self.binary_on_size_change
)
self.size_scale.set(self.cell_size)
self.size_scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
self.size_label = tk.Label(size_frame, text=f"{self.cell_size}px")
self.size_label.pack(side=tk.LEFT)
# 模式信息标签
self.binary_info_label = tk.Label(frame, text="", fg="green", font=("Arial", 9))
self.binary_info_label.pack(fill=tk.X, pady=5)
# ---------- 坐标模式选项卡 ----------
def create_coord_tab(self):
"""创建坐标模式的控制界面"""
frame = self.tab_coord
frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# ---- 文件选择区域 ----
file_frame = tk.LabelFrame(frame, text="坐标文件", padx=5, pady=5)
file_frame.pack(fill=tk.X, pady=(0, 5))
self.label_coord_file = tk.Label(
file_frame, text=f"默认: {self.coord_file_path}",
font=("Arial", 9), anchor="w"
)
self.label_coord_file.pack(fill=tk.X, pady=(0, 3))
btn_frame = tk.Frame(file_frame)
btn_frame.pack(fill=tk.X)
tk.Button(btn_frame, text="选择坐标文件", command=self.coord_select_file,
width=15).pack(side=tk.LEFT, padx=(0, 5))
# ---- 坐标信息显示 ----
info_frame = tk.LabelFrame(frame, text="坐标信息", padx=5, pady=5)
info_frame.pack(fill=tk.X, pady=5)
self.label_coord_count = tk.Label(
info_frame, text="已加载坐标: 0 个",
font=("Arial", 9), anchor="w"
)
self.label_coord_count.pack(fill=tk.X)
self.label_coord_range = tk.Label(
info_frame, text="X范围: -- ~ -- | Y范围: -- ~ --",
font=("Arial", 9), anchor="w"
)
self.label_coord_range.pack(fill=tk.X)
# ---- 画布设置 ----
setting_frame = tk.LabelFrame(frame, text="画布设置", padx=5, pady=5)
setting_frame.pack(fill=tk.X, pady=5)
# 画布大小
row1 = tk.Frame(setting_frame)
row1.pack(fill=tk.X, pady=2)
tk.Label(row1, text="画布大小:", width=10, anchor="w").pack(side=tk.LEFT)
self.entry_canvas_size = tk.Entry(row1, width=10)
self.entry_canvas_size.insert(0, str(self.coord_canvas_size))
self.entry_canvas_size.pack(side=tk.LEFT, padx=5)
tk.Label(row1, text="像素 (宽高相同)").pack(side=tk.LEFT)
# 边距
row2 = tk.Frame(setting_frame)
row2.pack(fill=tk.X, pady=2)
tk.Label(row2, text="边距:", width=10, anchor="w").pack(side=tk.LEFT)
self.entry_margin = tk.Entry(row2, width=10)
self.entry_margin.insert(0, str(self.coord_margin))
self.entry_margin.pack(side=tk.LEFT, padx=5)
tk.Label(row2, text="像素").pack(side=tk.LEFT)
# 点半径
row3 = tk.Frame(setting_frame)
row3.pack(fill=tk.X, pady=2)
tk.Label(row3, text="点半径:", width=10, anchor="w").pack(side=tk.LEFT)
self.radius_scale = tk.Scale(
row3, from_=1, to=10, orient=tk.HORIZONTAL,
command=self.coord_on_radius_change
)
self.radius_scale.set(self.coord_point_radius)
self.radius_scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
self.radius_label = tk.Label(row3, text=f"{self.coord_point_radius}px")
self.radius_label.pack(side=tk.LEFT)
# Y轴翻转
row4 = tk.Frame(setting_frame)
row4.pack(fill=tk.X, pady=2)
self.coord_flip_y_var = tk.BooleanVar(value=self.coord_flip_y)
tk.Checkbutton(
row4, text="Y轴翻转 (图像坐标系, 默认勾选)",
variable=self.coord_flip_y_var
).pack(anchor="w")
# ---- 操作按钮 ----
action_frame = tk.Frame(frame)
action_frame.pack(fill=tk.X, pady=5)
tk.Button(action_frame, text="生成图像", command=self.coord_generate,
width=12).pack(side=tk.LEFT, padx=2)
tk.Button(action_frame, text="保存图片", command=self.coord_save,
width=12).pack(side=tk.LEFT, padx=2)
# 模式信息标签
self.coord_info_label = tk.Label(frame, text="", fg="green", font=("Arial", 9))
self.coord_info_label.pack(fill=tk.X, pady=5)
# ============================================================
# 选项卡切换处理
# ============================================================
def on_tab_change(self, event):
"""切换标签页时更新预览和状态"""
tab = self.notebook.index(self.notebook.select())
if tab == 0: # 二进制模式
self.show_binary_preview()
self.status_label.config(
text="二进制模式 | " + (self.binary_info_label.cget("text") or "就绪"),
fg="green"
)
elif tab == 1: # 坐标模式
self.show_coord_preview()
self.status_label.config(
text="坐标模式 | " + (self.coord_info_label.cget("text") or "就绪"),
fg="green"
)
# ============================================================
# 预览更新(统一入口)
# ============================================================
def update_preview(self):
"""根据当前选项卡更新预览"""
tab = self.notebook.index(self.notebook.select())
if tab == 0:
self.show_binary_preview()
else:
self.show_coord_preview()
def show_binary_preview(self):
"""显示二进制模式的预览图像"""
if self.binary_preview:
self.current_photo = ImageTk.PhotoImage(self.binary_preview)
self.preview_label.config(image=self.current_photo, text="")
else:
self.preview_label.config(
image="", text="请输入二进制数据\n点击「生成二维码」",
font=("Arial", 12), fg="gray"
)
def show_coord_preview(self):
"""显示坐标模式的预览图像"""
if self.coord_preview:
self.current_photo = ImageTk.PhotoImage(self.coord_preview)
self.preview_label.config(image=self.current_photo, text="")
else:
self.preview_label.config(
image="", text="请选择坐标文件\n点击「生成图像」",
font=("Arial", 12), fg="gray"
)
# ============================================================
# 二进制模式方法(保留原二进制二维码生成.py全部功能)
# ============================================================
def binary_clear(self):
"""清空所有二进制数据"""
self.text_binary.delete("1.0", tk.END)
self.binary_string = ""
self.binary_matrix = []
self.binary_image_raw = None
self.binary_preview = None
self.binary_info_label.config(text="", fg="green")
self.update_preview()
def binary_load_file(self):
"""从文本文件加载二进制数据"""
file_path = filedialog.askopenfilename(
filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")]
)
if not file_path:
return
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read().strip()
# 只保留 0 和 1
clean = re.sub(r'[^01]', '', content)
if not clean:
messagebox.showerror("错误", "文件中未找到有效的二进制数据(仅0和1)")
return
self.text_binary.delete("1.0", tk.END)
self.text_binary.insert("1.0", clean)
self.binary_generate()
self.binary_info_label.config(
text=f"已加载 {len(clean)} 位二进制数据", fg="blue"
)
except Exception as e:
messagebox.showerror("错误", f"读取文件失败: {e}")
def binary_on_size_change(self, val):
"""格子大小滑块回调"""
self.cell_size = int(val)
self.size_label.config(text=f"{self.cell_size}px")
self.binary_generate()
def binary_generate(self):
"""根据文本框内容生成二维码图像并刷新预览"""
# 获取二进制字符串
raw = self.text_binary.get("1.0", tk.END).strip()
raw = re.sub(r'[^01]', '', raw) # 只保留0和1
if not raw:
self.binary_info_label.config(text="", fg="green")
self.binary_matrix = []
self.binary_string = ""
self.binary_image_raw = None
self.binary_preview = None
self.update_preview()
return
self.binary_string = raw
# 计算方形矩阵边长
bit_len = len(raw)
side = int(math.ceil(math.sqrt(bit_len)))
total_cells = side * side
# 补零至方阵
padded = raw.ljust(total_cells, '0')
# 构建二维矩阵
self.binary_matrix = []
for i in range(side):
row = []
for j in range(side):
idx = i * side + j
row.append(1 if padded[idx] == '1' else 0)
self.binary_matrix.append(row)
# 生成全尺寸图像
img_size = side * self.cell_size
img = Image.new('RGB', (img_size, img_size), color='white')
pixels_img = img.load()
assert pixels_img is not None, "PIL load() 返回了 None"
for i in range(side):
for j in range(side):
if self.binary_matrix[i][j] == 1:
for x in range(self.cell_size):
for y in range(self.cell_size):
pixels_img[
j * self.cell_size + x,
i * self.cell_size + y
] = (0, 0, 0)
self.binary_image_raw = img
# 缩放预览至最大400x400 (NEAREST 保持像素清晰)
display_size = min(400, img_size)
self.binary_preview = img.resize(
(display_size, display_size), Image.Resampling.NEAREST
)
# 更新预览显示
self.show_binary_preview()
# 更新信息
info_text = f"矩阵大小: {side}x{side} (原始位数: {bit_len}, 补零: {total_cells - bit_len})"
self.binary_info_label.config(text=info_text, fg="green")
self.status_label.config(
text=f"二进制模式 | {info_text}", fg="green"
)
def binary_save(self):
"""保存二进制生成的图像为PNG"""
if not self.binary_matrix:
messagebox.showwarning("警告", "没有可保存的二维码数据")
return
side = len(self.binary_matrix)
img_size = side * self.cell_size
img = Image.new('RGB', (img_size, img_size), color='white')
pixels_img = img.load()
assert pixels_img is not None, "PIL load() 返回了 None"
for i in range(side):
for j in range(side):
if self.binary_matrix[i][j] == 1:
for x in range(self.cell_size):
for y in range(self.cell_size):
pixels_img[
j * self.cell_size + x,
i * self.cell_size + y
] = (0, 0, 0)
file_path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG图片", "*.png"), ("所有文件", "*.*")]
)
if file_path:
img.save(file_path)
messagebox.showinfo("保存成功", f"图片已保存至:\n{file_path}")
# ============================================================
# 坐标模式方法(保留并增强原二维码画图.py功能)
# ============================================================
def coord_select_file(self):
"""选择坐标数据文件并加载"""
file_path = filedialog.askopenfilename(
filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")]
)
if not file_path:
return
self.coord_file_path = file_path
# 显示文件名(短路径)
short_name = file_path.split("/")[-1].split("\\")[-1]
self.label_coord_file.config(text=f"已选择: {short_name}")
# 加载并解析坐标
self.coord_load_file()
def coord_load_file(self):
"""从当前坐标文件路径加载并解析坐标数据"""
try:
points = []
with open(self.coord_file_path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
try:
tup = literal_eval(line)
if len(tup) >= 2:
x, y = tup[0], tup[1]
points.append((x, y))
except (SyntaxError, ValueError) as e:
print(f"跳过无效行 {line_num}: {line} ({e})")
if not points:
messagebox.showerror("错误", "文件中未找到有效的坐标数据")
return
self.coords = points
self.coord_loaded_count = len(points)
# 计算坐标范围
xs = [p[0] for p in points]
ys = [p[1] for p in points]
self.coord_min_x, self.coord_max_x = min(xs), max(xs)
self.coord_min_y, self.coord_max_y = min(ys), max(ys)
# 更新UI显示
self.label_coord_count.config(
text=f"已加载坐标: {self.coord_loaded_count} 个"
)
self.label_coord_range.config(
text=f"X范围: {self.coord_min_x} ~ {self.coord_max_x} | "
f"Y范围: {self.coord_min_y} ~ {self.coord_max_y}"
)
info_text = f"已加载 {self.coord_loaded_count} 个坐标点"
self.coord_info_label.config(text=info_text, fg="blue")
self.status_label.config(
text=f"坐标模式 | {info_text}", fg="blue"
)
except FileNotFoundError:
messagebox.showerror("错误", f"文件不存在: {self.coord_file_path}")
except Exception as e:
messagebox.showerror("错误", f"读取文件失败: {e}")
def coord_on_radius_change(self, val):
"""点半径滑块回调"""
self.coord_point_radius = int(val)
self.radius_label.config(text=f"{self.coord_point_radius}px")
# 如果已经生成过图像,自动重新生成
if self.coords:
self.coord_generate()
def coord_generate(self):
"""根据已加载坐标和当前设置生成图像"""
# 如果没有已加载坐标,尝试从文件加载
if not self.coords:
self.coord_load_file()
if not self.coords:
return
# 读取画布设置
try:
canvas_size = int(self.entry_canvas_size.get())
margin = int(self.entry_margin.get())
except ValueError:
messagebox.showerror("错误", "画布大小和边距必须为整数")
return
if canvas_size < 10 or margin < 0:
messagebox.showerror("错误", "画布大小至少为10,边距不能为负数")
return
if margin * 2 >= canvas_size:
messagebox.showerror("错误", "边距过大,无法绘图")
return
point_radius = self.coord_point_radius
flip_y = self.coord_flip_y_var.get()
# 计算缩放比例
range_x = self.coord_max_x - self.coord_min_x
range_y = self.coord_max_y - self.coord_min_y
if range_x == 0:
range_x = 1
if range_y == 0:
range_y = 1
scale_x = (canvas_size - 2 * margin) / range_x
scale_y = (canvas_size - 2 * margin) / range_y
# 创建画布并绘制
img = Image.new('RGB', (canvas_size, canvas_size), 'white')
draw = ImageDraw.Draw(img)
for (x, y) in self.coords:
px = margin + (x - self.coord_min_x) * scale_x
if flip_y:
# Y轴翻转:数据中较大的Y值对应图像上方
py = canvas_size - margin - (y - self.coord_min_y) * scale_y
else:
# 不翻转:保持原坐标方向
py = margin + (y - self.coord_min_y) * scale_y
draw.ellipse((
px - point_radius, py - point_radius,
px + point_radius, py + point_radius
), fill='black')
self.coord_image_raw = img
# 创建预览 (最大400x400, NEAREST缩放)
display_size = min(400, canvas_size)
self.coord_preview = img.resize(
(display_size, display_size), Image.Resampling.NEAREST
)
# 更新预览
self.show_coord_preview()
# 更新信息
info_text = (f"坐标数: {len(self.coords)} | "
f"画布: {canvas_size}x{canvas_size} | "
f"半径: {point_radius}px | "
f"{'翻转' if flip_y else '不翻转'}Y轴")
self.coord_info_label.config(text=info_text, fg="green")
self.status_label.config(
text=f"坐标模式 | {info_text}", fg="green"
)
def coord_save(self):
"""保存坐标生成的图像为PNG"""
if not self.coord_image_raw:
messagebox.showwarning("警告", "没有可保存的图像,请先生成图像")
return
file_path = filedialog.asksaveasfilename(
defaultextension=".png",
filetypes=[("PNG图片", "*.png"), ("所有文件", "*.*")]
)
if file_path:
self.coord_image_raw.save(file_path)
messagebox.showinfo("保存成功", f"图片已保存至:\n{file_path}")
if __name__ == "__main__":
root = tk.Tk()
app = UnifiedTool(root)
root.mainloop()