python写个验证码
发布时间:2020-12-20 12:49:03 所属栏目:Python 来源:网络整理
导读:用python写一个验证码功能 分析: 1、验证码背景 2、验证码包含26个字母大小写以及0-9十个数字 扩展需求:3、添加滤镜模糊等 ? 这里使用python中专门处理图片的PIL库 from PIL import ImageFont,ImageDraw,Image import random from io import BytesIO def g
用python写一个验证码功能 分析: 1、验证码背景 2、验证码包含26个字母大小写以及0-9十个数字 扩展需求:3、添加滤镜模糊等 ? 这里使用python中专门处理图片的PIL库 from PIL import ImageFont,ImageDraw,Image import random from io import BytesIO def get_random(): return random.randint(0,255),random.randint(0,255)RGB模式下的颜色信息 def get_code(request): img_obj=Image.new(‘RGB‘,(200,50),get_random()) 创建图片 img_draw=ImageDraw.Draw(img_obj) 生成画笔 img_font=ImageFont.truetype(‘static/font/333.ttf‘,50) 字体和文字大小 upper_str=chr(random.randint(65,90)) 利用ASCII码来生成大写小写的的文字 lower_str=chr(random.randint(97,122)) num_str=str(random.randint(0,9)) code=‘‘ for i in range(5): 每次随机拿出一个字母或者数字 res=random.choice([upper_str,lower_str,num_str]) img_draw.text((10+i*40,5),res,get_random(),img_font) code+=res io_obj=BytesIO() 生成二进制文件对象 img_obj.save(io_obj,‘png‘) 将生成的验证码图片存入文件对象中 request.session[‘code‘]=code print(code) return HttpResponse(io_obj.getvalue()) IO模块 即input、output 指的是文件的写入和读取 IO中的BytesIO方法是从内存中读写,咱们把生成的文件存入BytesIO对象中,需要的时候再用getvalue()的方法取出来 与之类似的还有StringIO,StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。 ?另附一个大佬写的验证码 #coding=utf-8 import random import string import sys import math from PIL import Image,ImageFont,ImageFilter #字体的位置,不同版本的系统会有不同 font_path = ‘/Library/Fonts/Arial.ttf‘ #生成几位数的验证码 number = 4 #生成验证码图片的高度和宽度 size = (100,30) #背景颜色,默认为白色 bgcolor = (255,255,255) #字体颜色,默认为蓝色 fontcolor = (0,255) #干扰线颜色。默认为红色 linecolor = (255,0) #是否要加入干扰线 draw_line = True #加入干扰线条数的上下限 line_number = (1,5) #用来随机生成一个字符串 def gene_text(): source = list(string.letters) for index in range(0,10): source.append(str(index)) return ‘‘.join(random.sample(source,number))#number是生成验证码的位数 #用来绘制干扰线 def gene_line(draw,width,height): begin = (random.randint(0,width),height)) end = (random.randint(0,height)) draw.line([begin,end],fill = linecolor) #生成验证码 def gene_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,height) # image = image.transform((width+30,height+10),Image.AFFINE,(1,-0.3,-0.1,1,0),Image.BILINEAR) #创建扭曲 image = image.transform((width+20,Image.BILINEAR) #创建扭曲 image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #滤镜,边界加强 image.save(‘idencode.png‘) #保存验证码图片 if __name__ == "__main__": gene_code() 转自https://www.cnblogs.com/yangdianfeng007/p/5438193.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |