
本文介绍如何使用 python 解析 esc/p(epson standard code for printers)协议中的位图打印指令(如 esc * 或 esc k),将其还原为可保存的黑白 bmp 图像,适用于无打印机场景下的嵌入式设备图像捕获与可视化。
ESC/P 是爱普生(Epson)定义的一套广泛用于针式/热敏打印机的控制协议,其中 ESC *(即 \x1b*)和 ESC K(即 \x1bK)是两种常见的单向位图打印命令,用于逐列发送 8 点阵(8-bit per column)的二值图像数据。当设备(如频谱分析仪 R&S CMS52、POS 打印终端等)通过串口输出 ESC/P 流而非连接真实打印机时,我们可以将其“重定向”为数字图像——这正是本教程的核心目标。
? 协议关键点解析
-
*`ESC 命令格式(标准 Epson)**: ESC * m nL nH [data...]`
- m = 0 表示 8-dot 单密度模式(最常用);
- nL, nH 是低位/高位字节,共同表示列数(num_columns = nH
- 后续 num_columns 个字节即为图像数据,每字节代表一列(bit7→bit0 对应该列从上到下 8 个像素)。
-
ESC K 命令格式(部分设备如 R&S CMS52 使用):
ESC K nL nH [data...]- 无 m 参数,直接跟两字节列数;
- 数据结构相同:每字节 = 一列,bit7 为顶点像素。
⚠️ 注意:原始代码中 data.find(b'\x1b*') 假设设备使用 ESC *,但实际设备(如 R&S CMS52)可能使用 ESC K,需根据硬件手册确认并调整起始标识符及参数偏移。
✅ 改进版健壮解析函数
以下为融合两种命令、增强容错性的 Python 实现(依赖 Pillow 和 struct):
from PIL import Image
import struct
def escp_to_bmp(data: bytes) -> bytes:
"""
将原始 ESC/P 串口数据(含 ESC * 或 ESC K 命令)解析为 BMP 二进制数据。
支持多图块拼接(连续 ESC/P 位图指令)。
"""
image_rows = [] # 存储所有行(每行是布尔列表,True=黑点)
pos = 0
data_len = len(data)
while pos < data_len:
# 尝试匹配 ESC *(\x1b\x2a)或 ESC K(\x1b\x4b)
if pos + 2 <= data_len and data[pos:pos+2] == b'\x1b*':
cmd_type = 'star'
header_end = pos + 5 # ESC * m nL nH → 共5字节头
elif pos + 2 <= data_len and data[pos:pos+2] == b'\x1bK':
cmd_type = 'k'
header_end = pos + 4 # ESC K nL nH → 共4字节头
else:
pos += 1
continue
# 检查 header 长度是否足够
if header_end > data_len:
break
# 提取列数
try:
if cmd_type == 'star':
# ESC * m nL nH → nL/nH 在 offset 3,4
nL, nH = data[header_end-2], data[header_end-1]
else: # 'k'
# ESC K nL nH → nL/nH 在 offset 2,3
nL, nH = data[pos+2], data[pos+3]
num_cols = (nH << 8) | nL
except IndexError:
break
# 检查图像数据长度是否足够
data_start = header_end if cmd_type == 'star' else pos + 4
data_end = data_start + num_cols
if data_end > data_len:
break
# 解析每列:每个字节 → 8 行(MSB 在上)
col_bytes = data[data_start:data_end]
for bit_pos in range(7, -1, -1): # 从 bit7(顶部)到 bit0(底部)
row = [(b >> bit_pos) & 1 for b in col_bytes]
image_rows.append(row)
# 更新读取位置:跳过整个指令(含命令+参数+数据)
pos = data_end + (2 if cmd_type == 'star' else 2) # ESC + * 或 ESC + K 占2字节
if not image_rows:
raise ValueError("No valid ESC/P bitmap command found in input data")
# 构建 PIL 图像:注意尺寸为 (width, height) = (列数, 行数)
width = len(image_rows[0]) if image_rows else 0
height = len(image_rows)
img = Image.new('1', (width, height)) # '1' mode = 1-bit black & white
# 展平为一维像素序列(行优先)
pixels = [pixel for row in image_rows for pixel in row]
img.putdata(pixels)
# 输出为 BMP 格式字节流
from io import BytesIO
buf = BytesIO()
img.save(buf, format='BMP')
return buf.getvalue()
# ✅ 使用示例
if __name__ == "__main__":
# 读取原始串口捕获文件(如用 PySerial 保存的 .bin)
with open("escp_capture.bin", "rb") as f:
raw = f.read()
try:
bmp_data = escp_to_bmp(raw)
with open("output.bmp", "wb") as f:
f.write(bmp_data)
print(f"✅ BMP saved successfully: {len(bmp_data)} bytes")
except Exception as e:
print(f"❌ Parsing failed: {e}")⚠️ 注意事项与调试建议
- 字节序与 unpack 陷阱:原始代码使用 struct.unpack('>BB', ...) 处理高低字节,但直接索引 data[i] 更简洁安全(避免 struct 对齐问题),推荐改用 nH
- 图像方向校验:ESC/P 列数据默认 top-to-bottom,因此 for bit_pos in range(7,-1,-1) 是正确的;若图像倒置,请检查 bit 解析顺序或调用 img.transpose(Image.FLIP_TOP_BOTTOM)。
- 多图块支持:本实现自动处理连续多个 ESC * / ESC K 命令,适用于长条码、分页报表等场景。
- 空白/控制字符过滤:真实串口流可能含 ESC d(纸退行)、ESC J(进纸)等非图像指令,当前逻辑自动跳过——仅识别并解析位图命令。
- 性能优化:对超大数据(如千列图像),可考虑使用 numpy 加速位操作,但 Pillow + 原生 Python 已满足大多数嵌入式日志解析需求。
? 总结
将 ESC/P 串口流转为 BMP 并非黑盒难题,核心在于精准识别命令标识、正确解释列数与位映射关系。本文提供了一套可直接运行、兼容主流设备(Epson 兼容机 & R&S CMS52)的健壮解析方案。开发者只需根据实际硬件文档微调命令前缀(* vs K),即可快速集成至数据采集系统、自动化测试平台或 Web 可视化后端中——让“打印机协议”真正成为“图像接口”。









