后端实现
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
def random_color():
"""
随机获取颜色
:return:
"""
return random.randint(0, 255), random.randint(10, 255), random.randint(64, 255)
def get_captcha(request):
"""
获取图片验证码
:param request:
:return:
"""
width = 150
height = 40
image = Image.new('RGB', size=(width, height),
color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
draw = ImageDraw.Draw(image, 'RGB')
font = ImageFont.truetype(r'C:\Windows\Fonts\Arial.ttf', 28)
for i in range(10):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=random_color())
for i in range(5):
a = str(random.randint(0, 9))
b = chr(random.randint(97, 122))
c = chr(random.randint(65, 90))
captcha = random.choice([a, b, c])
draw.text(xy=(25 + i * 20, 5), text=captcha, font=font,
fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255),))
for i in range(50):
draw.point([random.randint(0, width), random.randint(0, height)], fill=random_color())
f = BytesIO()
image.save(f, 'png')
data = f.getvalue()
return HttpResponse(data)
前端代码
<div class="col-sm-4 has-error">
<img src="/blog/get_captcha/" alt="">
</div>
效果图
