In this article, we share the example of Python website registration verification code generation class specific code for your reference, the details are as follows
# -*- coding:utf-8 -*- ''' Created on April 7, 2017 @author: water ''' import os import random import string import sys import math from PIL import Image,ImageDraw,ImageFont,ImageFilter from import settings The position of the #fonts will vary between versions of the system font_path = ('/home/workspace/aofeiKart/static', 'fonts/')#settings.STATIC_ROOT, 'fonts/') font_path = (settings.STATIC_ROOT, 'fonts/') # print font_path # Generate several-digit CAPTCHA number = 4 # Generate height and width of CAPTCHA images size = (100,30) # Background color, default is white bgcolor = (255,255,255) #Font color, default is blue fontcolor = (0,0,255) # Interference line color. Defaults to red. linecolor = (255,0,0) #Whether or not to include interference lines draw_line = True # Add upper and lower limits on the number of interference lines line_number = (1,5) # Used to generate a random string # source = list(string.ascii_lowercase+'1234567890') source = list('1234567890') def gene_text(): # return '6666' return ''.join((source,number))#number is the number of digits used to generate the CAPTCHA # Used to draw interference lines def gene_line(draw,width,height): begin = ((0, width), (0, height)) end = ((0, width), (0, height)) ([begin, end], fill = linecolor) # Generate CAPTCHA def gene_code(): width,height = size #Width and height image = ('RGBA',(width,height),bgcolor) #Creating Pictures font = (font_path,25) #Captcha fonts draw = (image) #Creating brushes text = gene_text() # Generate strings font_width, font_height = (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 = ((width+20,height+10), , (1,-0.3,0,-0.1,1,0), ) #Creating distortions image = (ImageFilter.EDGE_ENHANCE_MORE) #Filter, Boundary Enhancement image_file = text+'.png' image_path = (settings.STATIC_ROOT, 'images/%s'%image_file) (image_path) #SaveCaptcha image return ':8000/static/images/%s'%image_file, text if __name__ == "__main__": print gene_code()
The implementation process is simple, with 2 main points to note:
1. Install the PIL library, set the font save directory
2. If you return the binary data stream of the image directly, as follows:
buf = () #() #() use it to fill str obj (buf, 'png') ['captcha'] = () return HttpResponse((), 'image/png') # return the image data stream as image/jpeg format, browser will treat it as an image
This is the whole content of this article.