1
1

30pcs建立索引图.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import os
  2. import sys
  3. import re
  4. from PIL import Image, ImageDraw, ImageFont
  5. def parse_filename(filename):
  6. """从文件名中提取刀版编号、日期和尺寸(支持点/横杠日期、小数及 mm/cm 单位)"""
  7. base = os.path.splitext(filename)[0]
  8. # 1. 提取刀版编号 (例如: 98刀版)
  9. no_match = re.search(r'(\d+号?刀版)', base)
  10. no_text = no_match.group(1) if no_match else ""
  11. # 2. 提取日期:支持 2026.11.14 或 2026-11-14
  12. date_match = re.search(r'(\d{4}[.-]\d{1,2}[.-]\d{1,2})', base)
  13. date_text = date_match.group(1) if date_match else ""
  14. # 3. 提取尺寸:支持小数、mm/cm单位、多维尺寸 (例如: 80.5x60x320mm 或 12.5x10cm)
  15. dim_match = re.search(
  16. r'(\d+(?:\.\d+)?x\d+(?:\.\d+)?(?:x\d+(?:\.\d+)?)?\s*(?:mm|cm))',
  17. base,
  18. re.IGNORECASE,
  19. )
  20. dim_text = dim_match.group(1) if dim_match else ""
  21. # 组装两行:第一行放编号和日期,第二行放尺寸
  22. line1 = f"{no_text} {date_text}".strip()
  23. line2 = dim_text
  24. if not line1 and not line2:
  25. line1 = base[:15]
  26. line2 = ""
  27. return line1, line2
  28. def draw_bold_text(draw, xy, text, font, fill):
  29. """通过微量偏移实现文字加粗效果"""
  30. x, y = xy
  31. draw.text((x, y), text, font=font, fill=fill)
  32. draw.text((x + 1, y), text, font=font, fill=fill)
  33. def load_font(font_size=36):
  34. """加载中文字体"""
  35. font_paths = [
  36. "C:/Windows/Fonts/msyh.ttc", # Windows 微软雅黑
  37. "/System/Library/Fonts/PingFang.ttc", # macOS 苹方
  38. "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", # Linux
  39. ]
  40. for path in font_paths:
  41. if os.path.exists(path):
  42. try:
  43. return ImageFont.truetype(path, font_size)
  44. except Exception:
  45. pass
  46. return ImageFont.load_default()
  47. def render_group(group_files, directory, group_idx, total_groups, font, thumb_size=(400, 400), cols=5):
  48. """渲染单个分组(最多 30 张)的索引大图"""
  49. n = len(group_files)
  50. rows = (n + cols - 1) // cols
  51. padding = 5
  52. text_height = 90
  53. cell_width = thumb_size[0] + padding * 2
  54. cell_height = thumb_size[1] + text_height + padding * 2
  55. canvas_width = cols * cell_width + padding
  56. canvas_height = rows * cell_height + padding
  57. canvas = Image.new('RGB', (canvas_width, canvas_height), (255, 255, 255))
  58. draw = ImageDraw.Draw(canvas)
  59. color_line1 = (255, 0, 0) # 第一行:红色
  60. color_line2 = (0, 128, 255) # 第二行:蓝色
  61. drawn_count = 0
  62. for idx, file in enumerate(group_files):
  63. file_path = os.path.join(directory, file)
  64. line1, line2 = parse_filename(file)
  65. try:
  66. with Image.open(file_path) as img:
  67. img = img.convert('RGB')
  68. img.thumbnail(thumb_size, Image.Resampling.LANCZOS)
  69. row = idx // cols
  70. col = idx % cols
  71. x = col * cell_width + padding
  72. y = row * cell_height + padding
  73. thumb_bg = Image.new('RGB', thumb_size, (255, 255, 255))
  74. paste_x = (thumb_size[0] - img.width) // 2
  75. paste_y = (thumb_size[1] - img.height) // 2
  76. thumb_bg.paste(img, (paste_x, paste_y))
  77. canvas.paste(thumb_bg, (x + padding, y + padding))
  78. start_y = y + padding + thumb_size[1] + 8
  79. try:
  80. bbox1 = draw.textbbox((0, 0), line1, font=font)
  81. w1 = bbox1[2] - bbox1[0]
  82. except Exception:
  83. w1 = len(line1) * 11
  84. x1 = x + padding + (thumb_size[0] - w1) // 2
  85. draw_bold_text(draw, (x1, start_y), line1, font, color_line1)
  86. if line2:
  87. try:
  88. bbox2 = draw.textbbox((0, 0), line2, font=font)
  89. w2 = bbox2[2] - bbox2[0]
  90. except Exception:
  91. w2 = len(line2) * 11
  92. x2 = x + padding + (thumb_size[0] - w2) // 2
  93. draw_bold_text(draw, (x2, start_y + 40), line2, font, color_line2)
  94. drawn_count += 1
  95. except Exception as e:
  96. print(f"无法读取图片 {file}: {e}")
  97. if drawn_count == 0:
  98. print(f"第 {group_idx}/{total_groups} 组没有成功加载任何图片,已跳过。")
  99. return
  100. width_digits = max(2, len(str(total_groups)))
  101. output_name = f"index_overview_{group_idx:0{width_digits}d}.jpg"
  102. output_path = os.path.join(directory, output_name)
  103. canvas.save(output_path, quality=95)
  104. print(f"[{group_idx}/{total_groups}] 生成成功(本组 {drawn_count} 张): {output_path}")
  105. def create_index_images(directory, batch_size=30, thumb_size=(400, 400), cols=5):
  106. """按指定数量(默认 30 个文件一组)生成多张索引大图"""
  107. if not os.path.isdir(directory):
  108. print(f"错误: 目录 '{directory}' 不存在。")
  109. return
  110. valid_exts = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
  111. files = sorted([
  112. f for f in os.listdir(directory)
  113. if f.lower().endswith(valid_exts)
  114. and not re.match(r'^index_overview(?:_\d+)?\.jpg$', f, re.IGNORECASE)
  115. and os.path.isfile(os.path.join(directory, f))
  116. ])
  117. if not files:
  118. print("未在指定目录下找到支持的图片文件。")
  119. return
  120. batches = [files[i:i + batch_size] for i in range(0, len(files), batch_size)]
  121. total_groups = len(batches)
  122. font = load_font(36)
  123. print(f"共找到 {len(files)} 个图片文件,按每组 {batch_size} 个拆分为 {total_groups} 张索引图。")
  124. for group_idx, group_files in enumerate(batches, start=1):
  125. render_group(
  126. group_files=group_files,
  127. directory=directory,
  128. group_idx=group_idx,
  129. total_groups=total_groups,
  130. font=font,
  131. thumb_size=thumb_size,
  132. cols=cols,
  133. )
  134. if __name__ == "__main__":
  135. if len(sys.argv) < 2:
  136. print("用法: python DF2026返单钢刀索引大图.py <文件夹目录>")
  137. sys.exit(1)
  138. target_directory = sys.argv[1]
  139. create_index_images(target_directory, batch_size=30)