怎样用 Python 脚本批量生成 24 套服装配色并导出 PNG?

解读

面试官真正想考察的是:

  1. 对 Inkscape 自动化工作流的理解——能否脱离 GUI、用命令行或扩展脚本完成批量任务;
  2. 对 SVG 颜色模型与图层/对象 ID 命名规范的掌控——能否精准替换颜色而不破坏路径结构;
  3. 对 Python 生态的熟悉度——能否把 Inkscape、lxml、pillow 等工具链串成一条“读模板→改配色→导出 PNG”的闭环;
  4. 工程化思维——24 套只是最小集,脚本能否秒级扩展、日志可追溯、异常可回滚,满足国内服装企业“快反”节奏。

知识点

  1. SVG 本质是可编程的 XML,颜色值可集中写在 style 或 CSS 变量里,批量替换用 lxml.etree 即可,无需正则;
  2. Inkscape 1.x 之后官方推荐用“inkscape”命令行而非废弃的 inkex.py,关键参数: --export-type=png --export-filename --export-background-opacity=0 --export-dpi=300
  3. 国内服装公司常用 Pantone TCX 色卡,需提前把 24 组 TCX 转成 sRGB 十六进制,写进 JSON 配置,方便审版时快速对照;
  4. 若模板文件含克隆对象、滤镜、遮罩,直接改 fill 可能失效,需递归到子节点并同步改 stroke、filter 中的 FloodColor;
  5. 批量导出必须防“文件名撞车”,建议用“款号_色号_序号.png”三段式命名,方便后续 MES 系统扫码入库;
  6. Windows 环境下注意中文路径,需用 subprocess.run 的 encoding='utf-8' 与 Path.as_posix() 规避乱码;
  7. 日志要落盘,国内审版流程常半夜跑脚本,第二天版师追责,必须有“时间戳+旧值→新值”的 diff 记录;
  8. 版权合规:模板 SVG 若来自外购图库,脚本里要自动写入 metadata 字段,声明“仅内部打样使用”,避免侵权纠纷。

答案

下面给出一个可直接落地的 Python3 脚本骨架,假设模板文件“shirt_base.svg”里需要换色的对象已提前用图层命名“color_main”“color_secondary”“color_accent”。24 组配色写进 colors.json,脚本跑完后在 ./output 文件夹生成 24 张 300 dpi 透明底 PNG。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量给服装矢量模板换色并导出 PNG
依赖:lxml, pillow(可选,用于批量压缩), inkscape 1.x 已加入系统 PATH
"""
import json
import subprocess
from pathlib import Path
from lxml import etree

CONFIG = {
    "template": "shirt_base.svg",
    "palette": "colors.json",
    "out_dir": "output",
    "dpi": 300,
    "layers": ["color_main", "color_secondary", "color_accent"]
}

def load_palette(path):
    with open(path, encoding='utf-8') as f:
        return json.load(f)  # 格式:[{"name":"P123","main":"#FF0000","secondary":"#00FF00","accent":"#0000FF"},...]

def replace_colors(svg_path, color_dict, layers):
    tree = etree.parse(svg_path)
    ns = {'svg': 'http://www.w3.org/2000/svg',
          'inkscape': 'http://www.inkscape.org/namespaces/inkscape'}
    for layer_id in layers:
        layer = tree.xpath(f'//svg:g[@inkscape:label="{layer_id}"]', namespaces=ns)
        if not layer:
            continue
        color_key = layer_id.replace('color_', '')
        hex_color = color_dict[color_key]
        for node in layer[0].xpath('.//*[@style]', namespaces=ns):
            style = node.get('style')
            # 仅替换 fill 或 stroke 中的颜色,保留其余属性
            style = style.replace('fill:#000000', f'fill:{hex_color}')
            style = style.replace('stroke:#000000', f'stroke:{hex_color}')
            node.set('style', style)
    return tree

def export_png(svg_bytes, png_path):
    cmd = ['inkscape',
           '--export-type=png',
           f'--export-filename={png_path}',
           f'--export-dpi={CONFIG["dpi"]}',
           '--export-background-opacity=0',
           '/dev/stdin']
    subprocess.run(cmd, input=svg_bytes, check=True)

def main():
    palette = load_palette(CONFIG["palette"])
    Path(CONFIG["out_dir"]).mkdir(exist_ok=True)
    for idx, color_set in enumerate(palette, 1):
        tree = replace_colors(CONFIG["template"], color_set, CONFIG["layers"])
        svg_bytes = etree.tostring(tree, xml_declaration=True, encoding='UTF-8')
        png_name = f"shirt_{color_set['name']}.png"
        export_png(svg_bytes, Path(CONFIG["out_dir"]) / png_name)
        print(f"[{idx:02d}/24] {png_name} 导出完成")

if __name__ == '__main__':
    main()

运行前准备:

  1. 把 24 组 Pantone TCX 对应的 sRGB 十六进制录入 colors.json;
  2. 确保 inkscape 命令在 PATH,Windows 需把安装目录手动加到环境变量;
  3. 模板文件里图层命名与 CONFIG["layers"] 保持一致,若对象不在图层内,可改用 class 或 id 选择器。

拓展思考

  1. 如果 24 套要按“男款/女款/童款”三套廓形各 24 色,共 72 张,如何并行?可用 Python concurrent.futures 把 export_png 丢进进程池,Inkscape 本身无锁,能跑满 8 核,3 分钟出图;
  2. 客户临时把“撞色织带”从 1 条增加到 3 条,意味着模板可变参数维度升高,脚本如何不改代码?可把 layers 字段改成嵌套结构,支持“color_main_*”通配符,递归搜索;
  3. 国内工厂激光切割需要同时导出 1:1 的 DXF,脚本里可追加 --export-type=dxf,但 DXF 无颜色信息,需额外在文件名里缀上色号,方便工人分拣;
  4. 审版环节常要求“前片/后片/侧缝”分开展示,可在 SVG 里用 inkscape:groupmode="layer" 把每个部位单独打组,脚本循环可见性,一次性导出 24×3=72 张 PNG,自动拼成 6×4 的 A3 画板供打印;
  5. 版权与合规:若模板来自第三方,脚本跑完后自动在 PNG metadata 写入“Copyright 仅供内部打样”及当日时间戳,防止样衣外流被追责;
  6. 性能极限:当配色暴涨到 1000 套时,磁盘 IO 成为瓶颈,可把 SVG 放内存文件系统(tmpfs),导出 PNG 时直接写 WebP 再转 PNG,减少 40% 时间;
  7. 与 PLM 系统对接:脚本跑完把文件名、色号、MD5 写入 MySQL,版师在 PLM 里点击“查看矢量”按钮,系统反向调用 inkscape --shell 模式,实时回传 SVG 预览,实现“云审版”。

掌握以上思路,面试时不仅能答出“24 套”,还能主动抛出“72 套、1000 套、PLM 对接”的梯度方案,面试官会默认你具备“从设计到生产”全链路自动化视野,offer 概率直接拉满。