二维码
二维码生成
1.用法
https://github.com/lincolnloop/python-qrcode
2.使用
简单实用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import qrcode # 二维码内容 data = "https://www.baidu.com" # 生成二维码 img = qrcode.make(data=data) # 直接显示二维码 img.show() # 保存二维码为文件 # img.save("baidu.jpg")
设置参数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import qrcode # 实例化二维码生成类 qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) # 设置二维码数据 data = "https://www.baidu.com" qr.add_data(data=data) # 启用二维码颜色设置 qr.make(fit=True) img = qr.make_image(fill_color="green", back_color="white") # 显示二维码 img.show()
生成带图标的二维码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import qrcode from PIL import Image import matplotlib.pyplot as plt def getQRcode(data, file_name): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=5, border=4, ) # 添加数据 qr.add_data(data) # 填充数据 qr.make(fit=True) # 生成图片 img = qr.make_image(fill_color="green", back_color="white") # 添加logo,打开logo照片 icon = Image.open("logo.jpg") # 获取图片的宽高 img_w, img_h = img.size # 参数设置logo的大小 factor = 6 size_w = int(img_w / factor) size_h = int(img_h / factor) icon_w, icon_h = icon.size if icon_w > size_w: icon_w = size_w if icon_h > size_h: icon_h = size_h # 重新设置logo的尺寸 icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS) # 得到画图的x,y坐标,居中显示 w = int((img_w - icon_w) / 2) h = int((img_h - icon_h) / 2) # 黏贴logo照 img.paste(icon, (w, h), mask=None) # 终端显示图片 plt.imshow(img) plt.show() # 保存img img.save(file_name) return img if __name__ == '__main__': getQRcode("世情薄,人情恶,雨送黄昏花易落。晓风干,泪痕残,欲笺心事,独语斜阑。" "难,难,难!人成各,今非昨,病魂常似秋千索。角声寒,夜阑珊,怕人寻问,咽泪装欢。瞒,瞒,瞒!", 'my.png')
参考https://www.jianshu.com/p/c0073c6aa544
二维码识别
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import pyzbar.pyzbar as pyzbar from PIL import Image,ImageEnhance ''' 二维码识别 ''' image = "my.png" img = Image.open(image) #img = ImageEnhance.Brightness(img).enhance(2.0)#增加亮度 #img = ImageEnhance.Sharpness(img).enhance(17.0)#锐利化 #img = ImageEnhance.Contrast(img).enhance(4.0)#增加对比度 #img = img.convert('L')#灰度化 # img.show() barcodes = pyzbar.decode(img) for barcode in barcodes: barcodeData = barcode.data.decode("utf-8") print(barcodeData)