Python生成验证码

1.Python3.x中安装Pillow模块
pip install pillow

 

2.Python生成验证码(Python生成数字英文验证码, Python生成验证码,文章摘自: https://www.cnblogs.com)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'''
PIL(Python Imaging Library)是Python一个强大方便的图像处理库,名气也比较大。不过只支持到Python 2.7
在Python2中,PIL(Python Imaging Library)是一个非常好用的图像处理库,但PIL不支持Python3,所以有人(Alex Clark和Contributors)提供了Pillow,可以在Python3中使用。
Python3.x中安装Pillow模块:
    pip install pillow
'''
 
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import string
 
 
#生成4位验证码
def geneText():
    return ''.join(random.sample(string.ascii_letters + string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有数字0-9
 
 
#随机颜色
def rndColor():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
 
 
def drawLines(draw, num, width, height):
    '''划线'''
    for num in range(num):
        x1 = random.randint(0, width / 2)
        y1 = random.randint(0, height / 2)
        x2 = random.randint(0, width)
        y2 = random.randint(height / 2, height)
        draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
 
 
#生成验证码图形
def getVerifyCode():
    code = geneText()
    # 图片大小120×50
    width, height = 120, 50
    # 新图片对象
    im = Image.new('RGB', (width, height), 'white')
    # 字体库文件
    font = ImageFont.truetype('arial.ttf', 40)
    # draw对象
    draw = ImageDraw.Draw(im)
    # 绘制字符串
    for item in range(4):
        draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),text=code[item], fill=rndColor(), font=font)
    # 划线
    drawLines(draw, 2, width, height)
    im.save('code.jpg', 'jpeg')# 将生成的图片保存为code.jpg
    im.show()# 显示图片,第一次可能会提示选择默认图片查看器。
    print(im,code)
    return im, code
 
 
if __name__ == '__main__':
    getVerifyCode()

 

posted @   沉雪's  阅读(9)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示