Python implements the website registration verification code generation class


This article shares the specific code of Python website registration verification code generation class for your reference, the specific content is as follows

# -*- coding:utf-8 -*-
'''
Created on 2017 years 4 month 7 day

@author: Water
'''
import os
import random
import string
import sys
import math
from PIL import Image,ImageDraw,ImageFont,ImageFilter
from django.conf import settings


# Font locations vary from version to version of the system
font_path = os.path.join('/home/workspace/aofeiKart/static', 'fonts/monaco.ttf')#settings.STATIC_ROOT, 'fonts/MONACO.TTF')
font_path = os.path.join(settings.STATIC_ROOT, 'fonts/monaco.ttf')
# print font_path
# Generate a captcha of a few digits
number = 4
# The height and width of the generated captCHA image
size = (100,30)
# Background color, default to white
bgcolor = (255,255,255)
# Font color, default to blue
fontcolor = (0,0,255)
# Interference line color. Default is red
linecolor = (255,0,0)
# Whether to add interference lines
draw_line = True
# Add the upper and lower limits of the number of interfering lines
line_number = (1,5)

# For random generation 1 A string
# source = list(string.ascii_lowercase+'1234567890')
source = list('1234567890')
def gene_text():
#   return '6666'
  return ''.join(random.sample(source,number))#number Is the number of bits that generate the captcha
# Used to draw interference lines
def gene_line(draw,width,height):
  begin = (random.randint(0, width), random.randint(0, height))
  end = (random.randint(0, width), random.randint(0, height))
  draw.line([begin, end], fill = linecolor)

# Generate verification code
def gene_code():
  width,height = size # Width and height
  image = Image.new('RGBA',(width,height),bgcolor) # Create a picture
  font = ImageFont.truetype(font_path,25) # The font of the captcha
  draw = ImageDraw.Draw(image) # Create a brush
  text = gene_text() # Generate string
  font_width, font_height = font.getsize(text)
  draw.text(((width - font_width) / number, (height - font_height)/number),text,
      font= font,fill=fontcolor) # Fill string
  if draw_line:
    gene_line(draw,width,height)
  image = image.transform((width+20,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0), Image.BILINEAR) # Create distortions
  image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # Filter, boundary enhancement
  image_file = text+'.png'

  image_path = os.path.join(settings.STATIC_ROOT, 'images/%s'%image_file)

  image.save(image_path) # Save the captcha image

  return 'http://login.chaozu.net:8000/static/images/%s'%image_file, text

if __name__ == "__main__":
  print gene_code()

The implementation process is simple, and there are two main points to note:

1. Install the PIL library and set the fonts to save the directory

2. If the binary data stream of the image is returned directly, the following is true:

buf = io.BytesIO() #io.BytesIO() #io.StringIO() use it to fill str obj
image.save(buf, 'png')
request.session['captcha'] = text.lower()

return HttpResponse(buf.getvalue(), 'image/png') # return the image data stream as image/jpeg format, browser will treat it as an image