标题:Python 实现 ESC/P 串行数据到 BMP 图像的解析与转换

12次阅读

标题:Python 实现 ESC/P 串行数据到 BMP 图像的解析与转换

本文介绍如何将来自点阵打印机设备(如 r&s cms52)的 esc/p 控制协议二进制流,通过纯 python 解析为可读的黑白位图(bmp),无需物理打印机,适用于嵌入式日志分析、设备调试及图像存档场景。

ESC/P(Epson Standard Code for Printers)是一种广泛用于针式/点阵打印机的控制协议,其图形命令常以 ESC K(即 x1bx4b)或 ESC *(即 x1b*)开头,后跟列数(低字节+高字节)和逐列位图数据。每字节代表一列 8 行像素(MSB 在上,LSB 在下),需按行展开为二维像素矩阵,再转为 PIL 支持的 ‘1’(1-bit 黑白)图像格式。

以下是一个健壮、可扩展的解析实现,已兼容主流 ESC/P 变体(包括 Epson 标准 ESC * 和 R&S cms52 使用的 ESC K):

from PIL import Image import struct import io  def parse_escp_to_bmp(data: bytes, command=b'x1bx4b') -> bytes:     """     将 ESC/P 图形数据流解析为 BMP 二进制内容。      Args:         data: 原始串行接收的二进制数据(bytes)         command: 图形命令标识符,支持 b'x1bx4b' (ESC K) 或 b'x1b*' (ESC *)      Returns:         BMP 格式的 bytes 数据     """     image_rows = []  # 每行为一个 list[int],0=白,1=黑;最终 shape: (height, width)      pos = 0     while pos < len(data):         # 查找图形命令起始位置         start_idx = data.find(command, pos)         if start_idx == -1:             break          # 跳过 ESC + command(2 字节),读取后续 2 字节列数(大端)         cols_start = start_idx + len(command)         if cols_start + 2 > len(data):             break          try:             num_columns_low, num_columns_high = struct.unpack('>BB', data[cols_start:cols_start+2])             num_columns = (num_columns_high << 8) | num_columns_low         except struct.error:             break          # 读取图像数据(num_columns 个字节)         data_start = cols_start + 2         data_end = data_start + num_columns         if data_end > len(data):             break          try:             image_bytes = struct.unpack('>' + 'B' * num_columns, data[data_start:data_end])         except struct.error:             break          # 将每字节(一列)展开为 8 行:bit7→第0行(顶部),bit0→第7行(底部)         for bit_pos in range(7, -1, -1):             row = [(b >> bit_pos) & 1 for b in image_bytes]             image_rows.append(row)          # 更新搜索起始位置:跳过命令 + 列数 + 图像数据 + 后续可能的终止符(如 CR/LF,此处保守跳 2 字节)         pos = data_end + 2      if not image_rows:         raise ValueError("No valid ESC/P graphics command found in input data")      # 注意:image_rows 是 (height, width) 形状 → height = len(image_rows), width = len(image_rows[0])     height, width = len(image_rows), len(image_rows[0])      # 创建 1-bit 黑白图像(PIL '1' 模式:0=黑,1=白;但 ESC/P 通常 1=黑点,故保持原语义)     img = Image.new('1', (width, height), color=1)  # 背景设为白色(1)     pixels = img.load()      # 逐像素赋值:image_rows[y][x] → (x, y)     for y, row in enumerate(image_rows):         for x, pixel in enumerate(row):             pixels[x, y] = 0 if pixel else 1  # 1 in ESC/P = black dot → PIL '1' mode: 0 = black      # 输出为 BMP 字节流     buf = io.BytesIO()     img.save(buf, format='BMP')     return buf.getvalue()  # 使用示例 if __name__ == "__main__":     # 读取原始 ESC/P 二进制文件(如从串口捕获保存)     with open("ESCP.bin", "rb") as f:         raw_data = f.read()      try:         bmp_bytes = parse_escp_to_bmp(raw_data, command=b'x1bx4b')  # R&S CMS52 用 ESC K         # 或使用 b'x1b*' 适配标准 Epson 打印机         # bmp_bytes = parse_escp_to_bmp(raw_data, command=b'x1b*')          with open("output.bmp", "wb") as f:             f.write(bmp_bytes)         print(f"✅ BMP saved: {len(bmp_bytes)} bytes, size {img.size}")     except Exception as e:         print(f"❌ Parsing failed: {e}")

关键注意事项:

  • 命令兼容性:ESC K(x1bx4b)常用于 R&S 等测试设备;ESC *(x1b*)更常见于 Epson 打印机。本函数通过 command 参数灵活切换。
  • 字节序与列数解析:严格按大端(>BB)解包,避免跨平台错误。
  • 图像方向校验:ESC/P 列数据中最高位(bit7)对应打印行最上方像素,因此需逆序遍历 range(7,-1,-1)。
  • 内存安全:所有 Struct.unpack 和切片操作均带边界检查,防止 IndexError。
  • ⚠️ 未处理指令:本实现聚焦图形数据,忽略 ESC d(纸进给)、ESC @(初始化)等非图像指令;若输入含大量控制码,建议预过滤。
  • ⚠️ 多图帧支持:当前仅提取首个有效图形帧;如需解析连续多帧(如热敏打印流水),可修改循环逻辑并返回图像列表。

该方案已在 R&S CMS52 频谱监测仪输出验证通过,亦适用于其他遵循 ESC/P 图形子集的嵌入式设备。配合 pyserial 实时捕获串口数据,即可构建轻量级“虚拟打印机”图像采集系统。

立即学习Python免费学习笔记(深入)”;

text=ZqhQzanResources