要用Python生成二维码,首先需要下载一个Python的二维码库qrcode。qrcode库是用于生成二维码图像的Python第三方库。
qrcode二维码生成包安装如下(在命令行cmd中):
C:\> pipinstall qrcode
生成二维码图像同时依赖于PIL库。PIL(PythonImaging Library,图像处理类库)提供了通用的图像处理功能, 以及大量有用的基本图像操作,比如图像缩放、裁剪、旋转、颜色转换等。PIL是Python语言的第三方库,安装PIL库的方法如下,需要安装库的名字是pillow。
C:\> pipinstall pillow 或者 pip3install pillow
PIL 库支持图像存储、显示和处理,它能够处理几乎所有图片格式,可以完成对图像的缩放、剪裁、叠加以及向图像添加线条和文字等操作。
二维码生成和解析程序设计的步骤1. 生成带有图标的二维码
事先准备一个logo图标'logo.png'
使用下面程序生成带有logo图标的二维码。
import qrcode
from PIL import Image
import os, sys
def gen_qrcode(string, path,logo=''):
'''
生成中间带logo的二维码
需要安装qrcode, PIL库
@参数 string: 二维码字符串
@参数 path: 生成的二维码保存路径
@参数 logo: logo文件路径
@return: None
'''
# 初步生成二维码图像
qr =qrcode.QRCode(
version=2,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=8,
border=1
)
qr.add_data(string)
qr.make(fit=True)
# 获得Image实例并把颜色模式转换为RGBA
img =qr.make_image
img =img.convert('RGBA')
iflogo and os.path.exists(logo):
try:
icon = Image.open(logo) #打开填充的logo文件
img_w, img_h = img.size
except Exception as e:
print(e)
sys.exit(1)
factor = 4
#计算logo的尺寸
size_w = int(img_w / factor)
size_h = int(img_h / factor)
#比较并重新设置logo文件的尺寸
icon_w, icon_h = icon.size
if icon_w > size_w:
icon_w = size_w
if icon_h > size_h:
icon_h = size_h
icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
#计算logo的位置,并复制到二维码图像中
w= int((img_w - icon_w) / 2)
h= int((img_h - icon_h) / 2)
icon = icon.convert('RGBA')
img.paste(icon, (w, h), icon)
#保存二维码
img.save(path) #如'qrcode.png'
if __name__ == '__main__':
info= ' http://www. '
pic_path = 'qrcode.png' #生成的带有图标二维码图片
logo_path = 'logo.png' #用于填充的图标
gen_qrcode(info, pic_path,logo_path )
生成的带有图标二维码图片qrcode.png
2. Python解析二维码图片
解析二维码图片的信息需要使用zbarlight(二维码解析包),zbarlight安装如下:
pip install zbarlight
注意zbarlight二维码解析包仅仅支持Python2.7以下。
import zbar
defdecode_qrcode(path):
'''
解析二维码信息
@参数 path: 二维码图片路径
@return: 二维码信息
'''
scanner = zbar.ImageScanner #创建图片扫描对象
scanner.parse_config('enable') #设置对象属性
img =Image.open(path).convert('L') # 打开含有二维码的图片
width, height = img.size #获取图片的尺寸
# 建立zbar图片对象并扫描转换为字节信息
qrCode = zbar.Image(width, height, 'Y800', img.tobytes)
scanner.scan(qrCode)
# 组装解码信息
data= ''
for sin qrCode:
data += s.data
delimg # 删除图片对象
returndata # 输出解码结果
if __name__ == '__main__':
info= ' http://www. '
pic_path = 'qrcode.png' #生成的带有图标二维码图片
logo_path = 'logo.png' #用于填充的图标
gen_qrcode(info, pic_path,logo_path )
print(decode_qrcode(pic_path)) #得到二维码内的文本信息即网址http://www.
用Python生成 验证码图片
基本上大家使用每一种网络服务都会遇到验证码,一般是网站为了防止恶意注册、发帖而设置的验证手段。其生成原理是将一串随机产生的数字或符号,生成一幅图片,图片里加上一些干扰象素(防止OCR)。下面就详细讲解如何生成验证码。
除了配置好的Python环境外,还需要配有Python中的PIL库,这是python中专门用来处理图片的库。
要生成验证码图片,我们首先要生成一个随机字符串,包含26个字母和10个数字。
#用来随机生成一个字符串
defgene_text:
#source = list(string.letters)
#source =[ 'a', 'b', 'c', 'd', 'e', 'f','g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v','w', 'x', 'y', 'z']
source = list(string.ascii_letters)
for index in range(0,10):
source.append(str(index))
return''.join(random.sample(source,number)) #number是生成验证码的位数
然后我们要创建一个图片,写入字符串,需要说明的这里面的字体是不同系统而定,如果没有找到系统字体路径的话,也可以不设置。接下来,我们要在图片上画几条干扰线。
最后创建扭曲,加上滤镜,用来增强验证码的效果。下面是用程序生成的一个验证码。
完整的代码如下:
#coding=utf-8
importrandom,string, sys, math
from PIL importImage,ImageDraw,ImageFont,ImageFilter
font_path = ' C:\Windows\Fonts\simfang.ttf' #字体的位置
number = 4 #生成几位数的验证码
size =(80,30) #生成验证码图片的高度和宽度
bgcolor =(255,255,255) #背景颜色,默认为白色
fontcolor =(0,0,255) #字体颜色,默认为蓝色
linecolor =(255,0,0) #干扰线颜色。默认为红色
draw_line =True #是否要加入干扰线
line_number =(1,5) #加入干扰线条数的上下限
#用来随机生成一个字符串
defgene_text:
#source = list(string.letters)
#source =[ 'a', 'b', 'c', 'd', 'e', 'f','g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v','w', 'x', 'y', 'z']
source = list(string.ascii_letters)
for index in range(0,10):
source.append(str(index))
return''.join(random.sample(source,number))#number是生成验证码的位数
#用来绘制干扰线
defgene_line(draw,width,height):
begin = (random.randint(0, width),random.randint(0, height))
end = (random.randint(0, width),random.randint(0, height))
draw.line([begin, end], fill = linecolor)
#生成验证码
defgene_code:
width,height = size #宽和高
image =Image.new('RGBA',(width,height),bgcolor) #创建图片
font = ImageFont.truetype(font_path,25) #验证码的字体
draw = ImageDraw.Draw(image) #创建画笔
text = gene_text #生成字符串
font_width, font_height =font.getsize(text)
draw.text(((width - font_width) / number,(height - font_height) / number),text,
font= font,fill=fontcolor) #填充字符串
if draw_line:
gene_line(draw,width,height)
image = image.transform((width+20,height+10),Image.AFFINE,
(1,-0.3,0,-0.1,1,0),Image.BILINEAR) #创建扭曲
image =image.filter(ImageFilter.EDGE_ENHANCE_MORE) #滤镜,边界加强
image.save('idencode.png') #保存验证码图片
if __name__ =='__main__':
gene_code
上面的两个例子可见Python图像处理功能十分完善。 |
|
来自: 元东sntpxtmln9 > 《程序编程》