手搓一个验证码
import io import os import string from random import choice, randrange, sample from PIL import Image, ImageDraw, ImageFont def generate_captcha(): img_width = 58 img_height = 30 font_size = 16 font_color = ["black", "darkblue", "darkred"] background = (randrange(230, 255), randrange(230, 255), randrange(230, 255)) line_color = (randrange(0, 255), randrange(0, 255), randrange(0, 255)) current_path = os.path.dirname(os.path.abspath(__file__)) sample_file = os.path.join(current_path, "../static/fonts/LucidaSansDemiOblique.ttf") font = ImageFont.truetype(sample_file, font_size) img = Image.new("RGB", (img_width, img_height), background) captcha = "".join(sample(string.ascii_letters + string.digits, 4)) draw = ImageDraw.Draw(img) for i in range(randrange(3, 5)): xy = ( randrange(0, img_width), randrange(0, img_height), randrange(0, img_width), randrange(0, img_height), ) draw.line(xy, fill=line_color, width=1) x = 2 for i in captcha: y = randrange(0, 10) draw.text((x, y), i, font=font, fill=choice(font_color)) x += 14 buf = io.BytesIO() img.save(buf, "gif") buf.seek(0) return captcha, buf captcha, captcha_img = generate_captcha() # 验证码内容 存储到session, 返回图片展示 session["captcha"] = captcha.lower() return captcha_img
分类:
python(杂)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义