跳到正文

休闲·娱乐

公式画

Segment_Bugcat约 4 分钟
原文

这是 2026年8月5日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年8月5日
收录
2026年8月5日
更新
2026年11月14日
篇幅
约 4 分钟

版本

  1. v3当前
  2. v2
  3. v1
Python
#!/usr/bin/env python3
"""
图片 → LaTeX 彩色像素画(\colorbox,无额外宏包)
依赖:Pillow
用法:python img2latex_color_simple.py 照片.jpg --width 80 --pixel-size 4pt
"""

import argparse
from PIL import Image


def image_to_color_latex(image_path, width=80, pixel_size="4pt",
                         output="output.tex", full_document=False):
    # 1. 打开并转为 RGB
    img = Image.open(image_path).convert("RGB")
    orig_w, orig_h = img.size

    # 2. 按指定宽度缩放,保持长宽比
    new_w = width
    new_h = max(1, int(orig_h * width / orig_w))
    img_resized = img.resize((new_w, new_h), Image.NEAREST)
    pixels = img_resized.load()

    # 3. 构建 LaTeX 代码(不含任何 \usepackage)
    lines = []

    # 逐像素生成色块
    for y in range(new_h):
        row = []
        for x in range(new_w):
            r, g, b = pixels[x, y]
            hex_color = f"{r:02X}{g:02X}{b:02X}"
            # 不依赖额外宏包的彩色方块
            cell = "\\px{%s}" %hex_color
            row.append(cell)
        lines.append("$\\newcommand{\\px}[1]{\\color{#1}{\\rule{2pt}{2pt}}}" + "".join(row) + r"\\[-10.95pt]$ ")

    # 4. 写入文件
    with open(output, "w", encoding="utf-8") as f:
        f.write("".join(lines))
    print(f"✅ 已生成(无宏包):{output}  ({new_w}x{new_h},每块 {pixel_size})")
    if full_document:
        print("⚠️  编译前请确保已加载 color 或 xcolor 宏包(如在导言区加 \\usepackage{xcolor}),")
        print("   或在支持 \\colorbox 的环境中直接使用该文件。")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="图片 → LaTeX 彩色像素画(仅用 \colorbox,不导入宏包)"
    )
    parser.add_argument("image", help="输入图片路径")
    parser.add_argument("--width", type=int, default=80,
                        help="像素宽度(精度),默认 80")
    parser.add_argument("--pixel-size", default="4pt",
                        help="每个色块的大小,如 4pt, 2mm,默认 4pt")
    parser.add_argument("--output", default="output.tex",
                        help="输出 .tex 文件名,默认 output.tex")
    args = parser.parse_args()

    image_to_color_latex(
        args.image,
        width=args.width,
        pixel_size=args.pixel_size,
        output=args.output,
        full_document=False
    )