How does python generate web captCha

  • 2020-11-20 06:10:16
  • OfStack

This article shares the specific code of python generating web captcha for your reference. The specific content is as follows

Captcha is generated for pil module and can be directly applied to django framework.

First you need to install the Pillow module. The version we are using here is 3.4.1
Direct input instruction pip install Pillow==3.4.1 in terminal


from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO

def verify_code(request):
  # Introduce random function module 
  import random
  # Define variables for the background color, width, and height of the screen 
  bgcolor = (random.randrange(20, 100), random.randrange(
    20, 100), 255)
  width = 100
  height = 25
  # Create screen object 
  im = Image.new('RGB', (width, height), bgcolor)
  # Create a brush object 
  draw = ImageDraw.Draw(im)
  # To call the brush point() The function draws the noise 
  for i in range(0, 100):
    xy = (random.randrange(0, width), random.randrange(0, height))
    fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
    draw.point(xy, fill=fill)
  # Define alternative values for captchas 
  str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
  # Randomly selected 4 Value as a verification code 
  rand_str = ''
  for i in range(0, 4):
    rand_str += str1[random.randrange(0, len(str1))]
  # To construct a font object, ubuntu The font path is" /usr/share/fonts/truetype/freefont " 
  font = ImageFont.truetype('FreeMono.ttf', 23)
  # Construct font colors 
  fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
  # draw 4 A word 
  draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
  draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
  draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
  draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
  # Release the brush 
  del draw
  # deposit session , used for progress 1 Step to verify 
  request.session['verifycode'] = rand_str
  # Memory file operation 
  buf = BytesIO()
  # Store the image in memory, file type is png
  im.save(buf, 'png')
  # To return the image data in memory to the client, MIME Type is image png
  return HttpResponse(buf.getvalue(), 'image/png'

Related articles: