1 import random
2
3 def check_code(width=120, height=30, char_length=5, font_file='kumo.ttf', font_size=28):
4 code = []
5 img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
6 draw = ImageDraw.Draw(img, mode='RGB')
7
8 def rndChar():
9 """
10 生成随机字母
11 :return:
12 """
13 return chr(random.randint(65, 90))
14
15 def rndColor():
16 """
17 生成随机颜色
18 :return:
19 """
20 return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))
21
22 # 写文字
23 font = ImageFont.truetype(font_file, font_size)
24 for i in range(char_length):
25 char = rndChar()
26 code.append(char)
27 h = random.randint(0, 4)
28 draw.text([i * width / char_length, h], char, font=font, fill=rndColor())
29
30 # 写干扰点
31 for i in range(40):
32 draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
33
34 # 写干扰圆圈
35 for i in range(40):
36 draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
37 x = random.randint(0, width)
38 y = random.randint(0, height)
39 draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())
40
41 # 画干扰线
42 for i in range(5):
43 x1 = random.randint(0, width)
44 y1 = random.randint(0, height)
45 x2 = random.randint(0, width)
46 y2 = random.randint(0, height)
47
48 draw.line((x1, y1, x2, y2), fill=rndColor())
49
50 img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
51 return img,''.join(code)
52
53
54 if __name__ == '__main__':
55 # 1. 直接打开
56 # img,code = check_code()
57 # img.show()
58
59 # 2. 写入文件
60 # img,code = check_code()
61 # with open('code.png','wb') as f:
62 # img.save(f,format='png')
63
64 # 3. 写入内存(Python3)
65 # from io import BytesIO
66 # stream = BytesIO()
67 # img.save(stream, 'png')
68 # stream.getvalue()
69
70 # 4. 写入内存(Python2)
71 # import StringIO
72 # stream = StringIO.StringIO()
73 # img.save(stream, 'png')
74 # stream.getvalue()
75
76 pass
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?