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
标签:randrange,img,width,一个,验证码,captcha,font,255
From: https://www.cnblogs.com/gatling/p/18408794