码迷,mamicode.com
首页 > 编程语言 > 详细

Python生成验证码

时间:2019-09-12 21:54:42      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:center   div   水平   字符   class   bdd   har   cli   for   

技术图片
 1 """ Python生成静态验证码 """
 2 from captcha.image import ImageCaptcha
 3 import numpy as np
 4 import matplotlib.pyplot as plt
 5 from PIL import Image
 6 import random
 7 
 8 # 定义验证码中的字符
 9 number = [‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]
10 alphabet = [‘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‘]
11 ALPHABET = [‘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‘]
12 
13 # 随机生成验证码文本,验证码长度4字符
14 def random_captcha_text(char_set = number + alphabet + ALPHABET, captcha_size=4):
15     captcha_text = []
16     for i in range(captcha_size):
17         c = random.choice(char_set)
18         captcha_text.append(c)
19     return captcha_text
20 
21 # 生成字符对应的验证码
22 def gen_captcha_text_and_image():
23     image = ImageCaptcha()
24     captcha_text = random_captcha_text()
25     captcha_text = ‘‘.join(captcha_text)
26     captcha = image.generate(captcha_text)
27     captcha_image = Image.open(captcha)
28     captcha_image = np.array(captcha_image)
29     return captcha_text, captcha_image
30 
31 # 测试
32 if __name__ == ‘__main__‘:
33     text, image = gen_captcha_text_and_image()
34     f = plt.figure()
35     ax = f.add_subplot(111)  # 参数111:将画布分割成1行2列,图像画在第1块。
36     ax.text(0.1, 0.9, text, ha=‘center‘, va=‘center‘, transform=ax.transAxes)  # ha:水平分布情况 va:垂直分布情况 transform:指定text在图片中的相对位置。
37     plt.imshow(image)
38 
39     plt.show()
Python生成验证码

 

Python生成验证码

标签:center   div   水平   字符   class   bdd   har   cli   for   

原文地址:https://www.cnblogs.com/Junlong/p/11515036.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!