我通过串行接口从设备接收 ESC/P 协议。该设备实际上旨在连接到点阵打印机。由于我们不想使用打印机,因此我目前正在研究一种解决方案,通过软件接收流并将其保存在 BMP 文件中以供进一步使用。 我在网上搜索了很长一段时间,寻找有关该主题的 Python 库或其他解决方案,但遗憾的是没有找到任何内容。 所以我阅读了 ESC/P 协议并尝试编写自己的 Python 例程。如果其他人也遇到同样的问题,我会在这里发布我的解决方案。 我很高兴收到反馈或改进建议。
from PIL import Image
import struct, io
def parse_ESCP_bytes(data):
image_list = []
while data:
# Search for the start character (ESC) and the ASCII asterisk
start_index = data.find(b'\x1b*')
if start_index != -1:
# Extract the number of columns with the low and high bytes
num_columns_low, num_columns_high = struct.unpack('>BB', data[start_index+3:start_index+5])
num_columns = (num_columns_high << 8) + num_columns_low
# Read all bytes of the image data
image_data = struct.unpack('>' + 'B' * num_columns, data[start_index + 5:start_index + 5 + num_columns])
# The image data has the following format:
# [0, 7, 15, ...] each 8-bit value represents a column with 8 rows.
# 0 = No pixels, 7 = pixels 6, 7, 8 of this column are set (counted from the top).
# Thus, for each image data row we read, 8 new image rows are added to our list
for i in range(7, -1, -1):
image_list.append([col >> i & 1 for col in image_data])
# Update the data for the next iteration
data = data[start_index + 5 + num_columns + 2:]
# Control characters for DPI or paper feed or carriage return are not considered here.
else:
break
# Define the width and height of the pixel matrix
width, height = len(image_list), len(image_list[0])
# Create the binary black and white image
img = Image.new('1', (width, height))
# Set the pixels based on the pixel matrix
img.putdata([int(pixel) for row in image_list for pixel in row])
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='BMP')
return img_byte_arr.getvalue()
with open("ESCP", "rb") as file:
raw_serial = file.read()
image_bytes = parse_ESCP_bytes(raw_serial)
with open("output.bmp", 'wb') as file:
file.write(image_bytes)
非常感谢您的代码。我有一台 R&S CMS52,必须更改一些东西:
start_index = data.find(b'\x1b\x4b')
num_columns_low, num_columns_high = struct.unpack('>BB', data[start_index+2:start_index+4])
image_data = struct.unpack('>' + 'B' * num_columns, data[start_index + 4:start_index + 4 + num_columns])
数据 = 数据[起始索引 + 4 + 列数 + 2:]
img = Image.new('1', (高度,宽度))
再见,安德烈亚斯