|
发表于 2021-3-17 17:06:19
|
显示全部楼层
本楼为最佳答案
本帖最后由 YunGuo 于 2021-3-17 17:12 编辑
pylibdmtx库可以生成/解析DataMatrix二维码,生成的二维码图片背景是白色有边缘(有些网站生成二维码是透明背景没有边缘,比如草料)
- from PIL import Image
- from pylibdmtx import pylibdmtx
- # 生成data matrix二维码
- en = pylibdmtx.encode('http://www.baidu.com/'.encode('utf-8'))
- img = Image.frombytes('RGB', (en.width, en.height), en.pixels)
- img.save('444.png')
复制代码
pylibdmtx库生成的二维码可以直接解析出来,其它网站生成的二维码必须要有边缘(边框,或者二维码在一张图片中),不能是没有边框的纯二维码,不然会解析不出来;
- from PIL import Image
- from pylibdmtx import pylibdmtx
- # 加载图片
- image = Image.open('444.png')
- # 解析data matrix二维码
- de = pylibdmtx.decode(image)
- result = (de[0].data).decode('utf-8')
- print(result)
复制代码
如果只是纯二维码,没有边缘(边框),要想解析,目前想到的办法是先给图片添加一个边框(任何颜色都行)再去解析。
- from PIL import Image
- from pylibdmtx import pylibdmtx
- image = Image.open('1-666.png')
- # 获取图片宽高
- width, height = image.size
- # 添加边框
- width += 2 * 10
- height += 2 * 10
- new_img = Image.new('RGB', (width, height), (255, 255, 255))
- new_img.paste(image, (10, 10))
- # 解析二维码
- de = pylibdmtx.decode(new_img)
- result = (de[0].data).decode('utf-8')
- print(result)
复制代码 |
-
草料生成的(原图是透明背景,论坛好像没法传透明图,我转成了白色背景):
-
pylibdmtx生成的
|