Python在Shell中打印二维码

标签:
linuxpythonqr二维码pil |
分类: Linux |
原创作品欢迎转载,转载时请注明转载地址
在Shell中打印二维码
使用Python的PIL图像库读取图片的像素点值然后在shell窗口中打印特殊字符组成二维码。
如下图:在二维码的构成中相邻上下两个点之间只有四种构成情况。
所以使用blocks = {'0':"█",'1':"▄",'2':"?",'3':" ",}
具体实现代码如下:
from PIL import Image
IMG = "QR.jpg"
WIDTH = 430
HEIGHT = 430
OUTPUT = "out.txt"
#构成的字典集
blocks = {'0':"█",'1':"▄",'2':"?",'3':" ",}
def selc_cub(num):
return blocks.get(num);
def draw_QR():
global sel_num
im = Image.open(IMG)
im = im.resize((WIDTH,HEIGHT), Image.NEAREST)
txt = ""
#遍历整张图片
for i in range(0,HEIGHT-20,20):
for j in range(0,WIDTH,10):
if (im.getpixel((j+5,i+15)) > 128 ):
sel_num = 2;
#txt += " ";
else:
sel_num = 0;
#txt += "#";
if (im.getpixel((j,i)) > 128 ):
sel_num = sel_num + 1;
#txt += " ";
txt += selc_cub(str(sel_num))
#txt += get_char(*im.getpixel((j,i)))
#print txt
txt += '\n'
print txt
print "Done"
print " "
draw_QR()
运行程序之后在shell中打印的效果如下图
可能是字符编码的关系导致字符间间隔较大所以在shell中打印出来的二维码使用二维码扫描工具识别不了的。
但是在windows的Python
IDE的shell窗口打印出来的二维码倒是很标准这是和显示窗口的字符集有关。
使用python里面向shell输出彩色字符串模式打印“无缝”二维码
首先请参考这个链接
atrr = 7
fore = 37
back = 47
color_block = "\x1B[%d;%d;%dm" % (atrr,fore,back)
atrr = 0
fore = 0
back = 0
color_none = "\x1B[%d;%d;%dm" % (atrr,fore,back)
for loop in range(0,len(QR_Tab)):
if QR_Tab[loop] == '#' :
tmp_text = "%s \x1B[0m" %(color_block)
elif QR_Tab[loop] == ' ' :
tmp_text = "%s \x1B[0m" %(color_none)
else:
tmp_text = "\n"
print_tex = print_tex + tmp_text
代码实现如下:
from PIL import Image
IMG = "QR.jpg"
WIDTH = 430
HEIGHT = 430
OUTPUT = "out.txt"
def derw_QR(QR_Tab):
global tmp_text
global print_tex
tmp_text = ""
print_tex = ""
atrr = 7
fore = 37
back = 47
color_block = "\x1B[%d;%d;%dm" % (atrr,fore,back)
atrr = 0
fore = 0
back = 0
color_none = "\x1B[%d;%d;%dm" % (atrr,fore,back)
for loop in range(0,len(QR_Tab)):
if QR_Tab[loop] == '#' :
tmp_text = "%s \x1B[0m" %(color_block)
elif QR_Tab[loop] == ' ' :
tmp_text = "%s \x1B[0m" %(color_none)
else:
tmp_text = "\n"
print_tex = print_tex + tmp_text
#print_tex = "%s1\x1B[0m%s2\x1B[0m" %(color1,color2)
print print_tex
def get_imgdata():
global sel_num
global off_set
off_set = 0
im = Image.open(IMG)
im = im.resize((WIDTH,HEIGHT), Image.NEAREST)
txt = ""
for i in range(30,HEIGHT-10,10):
for j in range(30,WIDTH-10,10):
if (im.getpixel((j-5,i-5)) > 128 ):
txt += "#";
else:
txt += " ";
#txt += get_char(*im.getpixel((j,i)))
#print txt
txt += '\n'
return txt
# print txt
derw_QR(get_imgdata())
实现效果如下:
效果还是蛮“喜人”的,在shell窗口中完美无缝打印。
后一篇:百度语音的合成