国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現網站注冊驗證碼生成類

2019-11-25 16:06:54
字體:
來源:轉載
供稿:網友

本文實例為大家分享了Python網站注冊驗證碼生成類的具體代碼,供大家參考,具體內容如下

# -*- coding:utf-8 -*-'''Created on 2017年4月7日@author: Water'''import osimport randomimport stringimport sysimport mathfrom PIL import Image,ImageDraw,ImageFont,ImageFilterfrom django.conf import settings #字體的位置,不同版本的系統會有不同font_path = os.path.join('/home/workspace/aofeiKart/static', 'fonts/monaco.ttf')#settings.STATIC_ROOT, 'fonts/MONACO.TTF')font_path = os.path.join(settings.STATIC_ROOT, 'fonts/monaco.ttf')# print font_path#生成幾位數的驗證碼number = 4#生成驗證碼圖片的高度和寬度size = (100,30)#背景顏色,默認為白色bgcolor = (255,255,255)#字體顏色,默認為藍色fontcolor = (0,0,255)#干擾線顏色。默認為紅色linecolor = (255,0,0)#是否要加入干擾線draw_line = True#加入干擾線條數的上下限line_number = (1,5) #用來隨機生成一個字符串# source = list(string.ascii_lowercase+'1234567890')source = list('1234567890')def gene_text():#   return '6666'  return ''.join(random.sample(source,number))#number是生成驗證碼的位數#用來繪制干擾線def gene_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) #生成驗證碼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,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_file = text+'.png'    image_path = os.path.join(settings.STATIC_ROOT, 'images/%s'%image_file)  image.save(image_path) #保存驗證碼圖片    return 'http://login.chaozu.net:8000/static/images/%s'%image_file, textif __name__ == "__main__":  print gene_code()

實現過程很簡單,主要注意有2點:

1.安裝PIL庫,設置好字體保存目錄

2.如果直接返回圖片的二進制數據流的

主站蜘蛛池模板: 昌邑市| 正镶白旗| 吴堡县| 东乡族自治县| 奉化市| 襄垣县| 曲阜市| 肇州县| 陇南市| 彰化市| 秀山| 德庆县| 合阳县| 晋城| 太保市| 盈江县| 博乐市| 炉霍县| 弋阳县| 台山市| 蚌埠市| 辛集市| 防城港市| 和龙市| 米泉市| 普兰店市| 通海县| 高邮市| 洞口县| 福泉市| 黄大仙区| 海伦市| 内丘县| 从江县| 鱼台县| 轮台县| 珲春市| 偃师市| 泸溪县| 双流县| 城市|