import os import sys import re from PIL import Image, ImageDraw, ImageFont def parse_filename(filename): """从文件名中提取刀版编号、日期和尺寸(支持点/横杠日期、小数及 mm/cm 单位)""" base = os.path.splitext(filename)[0] # 1. 提取刀版编号 (例如: 98刀版) no_match = re.search(r'(\d+号?刀版)', base) no_text = no_match.group(1) if no_match else "" # 2. 提取日期:支持 2026.11.14 或 2026-11-14 date_match = re.search(r'(\d{4}[.-]\d{1,2}[.-]\d{1,2})', base) date_text = date_match.group(1) if date_match else "" # 3. 提取尺寸:支持小数、mm/cm单位、多维尺寸 (例如: 80.5x60x320mm 或 12.5x10cm) dim_match = re.search( r'(\d+(?:\.\d+)?x\d+(?:\.\d+)?(?:x\d+(?:\.\d+)?)?\s*(?:mm|cm))', base, re.IGNORECASE, ) dim_text = dim_match.group(1) if dim_match else "" # 组装两行:第一行放编号和日期,第二行放尺寸 line1 = f"{no_text} {date_text}".strip() line2 = dim_text if not line1 and not line2: line1 = base[:15] line2 = "" return line1, line2 def draw_bold_text(draw, xy, text, font, fill): """通过微量偏移实现文字加粗效果""" x, y = xy draw.text((x, y), text, font=font, fill=fill) draw.text((x + 1, y), text, font=font, fill=fill) def load_font(font_size=36): """加载中文字体""" font_paths = [ "C:/Windows/Fonts/msyh.ttc", # Windows 微软雅黑 "/System/Library/Fonts/PingFang.ttc", # macOS 苹方 "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", # Linux ] for path in font_paths: if os.path.exists(path): try: return ImageFont.truetype(path, font_size) except Exception: pass return ImageFont.load_default() def render_group(group_files, directory, group_idx, total_groups, font, thumb_size=(400, 400), cols=5): """渲染单个分组(最多 30 张)的索引大图""" n = len(group_files) rows = (n + cols - 1) // cols padding = 5 text_height = 90 cell_width = thumb_size[0] + padding * 2 cell_height = thumb_size[1] + text_height + padding * 2 canvas_width = cols * cell_width + padding canvas_height = rows * cell_height + padding canvas = Image.new('RGB', (canvas_width, canvas_height), (255, 255, 255)) draw = ImageDraw.Draw(canvas) color_line1 = (255, 0, 0) # 第一行:红色 color_line2 = (0, 128, 255) # 第二行:蓝色 drawn_count = 0 for idx, file in enumerate(group_files): file_path = os.path.join(directory, file) line1, line2 = parse_filename(file) try: with Image.open(file_path) as img: img = img.convert('RGB') img.thumbnail(thumb_size, Image.Resampling.LANCZOS) row = idx // cols col = idx % cols x = col * cell_width + padding y = row * cell_height + padding thumb_bg = Image.new('RGB', thumb_size, (255, 255, 255)) paste_x = (thumb_size[0] - img.width) // 2 paste_y = (thumb_size[1] - img.height) // 2 thumb_bg.paste(img, (paste_x, paste_y)) canvas.paste(thumb_bg, (x + padding, y + padding)) start_y = y + padding + thumb_size[1] + 8 try: bbox1 = draw.textbbox((0, 0), line1, font=font) w1 = bbox1[2] - bbox1[0] except Exception: w1 = len(line1) * 11 x1 = x + padding + (thumb_size[0] - w1) // 2 draw_bold_text(draw, (x1, start_y), line1, font, color_line1) if line2: try: bbox2 = draw.textbbox((0, 0), line2, font=font) w2 = bbox2[2] - bbox2[0] except Exception: w2 = len(line2) * 11 x2 = x + padding + (thumb_size[0] - w2) // 2 draw_bold_text(draw, (x2, start_y + 40), line2, font, color_line2) drawn_count += 1 except Exception as e: print(f"无法读取图片 {file}: {e}") if drawn_count == 0: print(f"第 {group_idx}/{total_groups} 组没有成功加载任何图片,已跳过。") return width_digits = max(2, len(str(total_groups))) output_name = f"index_overview_{group_idx:0{width_digits}d}.jpg" output_path = os.path.join(directory, output_name) canvas.save(output_path, quality=95) print(f"[{group_idx}/{total_groups}] 生成成功(本组 {drawn_count} 张): {output_path}") def create_index_images(directory, batch_size=30, thumb_size=(400, 400), cols=5): """按指定数量(默认 30 个文件一组)生成多张索引大图""" if not os.path.isdir(directory): print(f"错误: 目录 '{directory}' 不存在。") return valid_exts = ('.jpg', '.jpeg', '.png', '.bmp', '.webp') files = sorted([ f for f in os.listdir(directory) if f.lower().endswith(valid_exts) and not re.match(r'^index_overview(?:_\d+)?\.jpg$', f, re.IGNORECASE) and os.path.isfile(os.path.join(directory, f)) ]) if not files: print("未在指定目录下找到支持的图片文件。") return batches = [files[i:i + batch_size] for i in range(0, len(files), batch_size)] total_groups = len(batches) font = load_font(36) print(f"共找到 {len(files)} 个图片文件,按每组 {batch_size} 个拆分为 {total_groups} 张索引图。") for group_idx, group_files in enumerate(batches, start=1): render_group( group_files=group_files, directory=directory, group_idx=group_idx, total_groups=total_groups, font=font, thumb_size=thumb_size, cols=cols, ) if __name__ == "__main__": if len(sys.argv) < 2: print("用法: python DF2026返单钢刀索引大图.py <文件夹目录>") sys.exit(1) target_directory = sys.argv[1] create_index_images(target_directory, batch_size=30)