Skip to main content
 首页 » 编程设计

python之如何将数据矩阵代码从 hubarcode 转换为 PILimage

2025年05月04日11xiaohuochai

我正在尝试使用 hubarcode package 将字符串编码为 DataMatrix .我想将 en 对象转换为 PIL 图像,以便我可以在下游进一步使用它。

如果我阅读 this function正确地定义了 get_pilimage(),我认为 en.get_pilimage() 应该可以工作,但当然不行。当我检查 dir(en) 时,未定义 get_pilimage(仅 get_imagedata 和 get_ascii)。这是因为 get_pilimage 没有在 __init__.py for DataMatrixRenderer 中定义吗? ?

这是我使用的代码

# pip install huBarcode 
from hubarcode.datamatrix import DataMatrixEncoder 
en = DataMatrixEncoder("M103") 
en.get_imagedata() # result below 
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00F\x00\x00\x00F\x08\x00\x00\x00\x00TE\xbdX\x00\x00\x00\x9aIDATx\x9c\xed\x98\xc1\n\xc00\x08Cu\xf4\xff\x7f\xb9\xbbM\x16t\xb3\xc3CV\xcc\xc9ayh\x10i\xa7S*t\x94P\x1a\xd3\x98O\x1a\x16\xaa\x88\xc8\\\x89\xca\xab\xd9\x12\xa3\xe6\x95^Q\xe8d\xe83WS\\\x98\x01\xdf\x9e\xa7\x90\xed)^\x13Zl\xfe=\x9b\xddS\x9c\x16Z\x0c\x82\xe5\x01Qy5[b\xdcE\xe1me\xb9G\x96\xad\xacfK\xcc\xcb\x14\x87\xea]\x9cV|\xa3\xc0\x83W\xc2;\xc7\xd5\x14\x17\xc6\xb5\x18\x94x\x00r5\xc5\x85\xc9,\x8a\x84\xf7\\Mqa\xb4\xffQ4\xe6\xf7\x98\x13\xd1\xa9\x1f\x8e\x11\x9b\xc5\x81\x00\x00\x00\x00IEND\xaeB`\x82' 
 
en.get_pilimage() # doesn't work, but I imagine result would be an image 

或者,是否有另一种方法可以将 en.get_imagedata() 的结果转换为 png?

请您参考如下方法:

我最终获取了原始图像字符串,将其转换为 BytesIO 对象并将流传递给 PIL.Image。

import io 
import PIL 
from hubarcode.datamatrix import DataMatrixEncoder 
 
dm = DataMatrixEncoder("M103") 
dm_in_bytes = io.BytesIO(dm.get_imagedata()) 
img = PIL.Image.open(dm_in_bytes) 
 
img.show()