The random codes generated BBS

Generating a random codes

views.py

First you need to download a pillow block pip3 install pillow

from the PIL Import Image, ImageDraw, ImageFont
 # Import module pillow 
'' '
Image: Image generation
ImageDraw: to write something in the picture is equivalent to brush
ImageFont: control font styles
'''

from  io import BytesIO,StringIO
'''
io is a memory manager module
BytesIO can help you to store data in binary format
StringIO can help you to store data in a format string
'''

Import Random
 DEF get_random ():     # in order to obtain such colors using random numbers (255,255,255) 
    return the random.randint (0,255), the random.randint (0,255), the random.randint (0,255)

 

 

Next to the picture generated random verification code

def get_code(request):

    img_obj = Image.new ( ' the RGB ' , (360,35 ), get_random ()) 
     # can generate any of a plurality of different color images, color image format 2. 1. Image size (width, height) 3. Color random number here generating, for example, (20,30,42) 

    img_draw = ImageDraw.Draw (image) # generates a write in the picture on the brush 
    img_font = ImageFont.truetype ( ' static / font / 111.ttf ' , 30) # decision fonts 1. 2. font size font style

    # The following five random codes generated and written in the image img_obj 
    
    code = '' 
    for I   in Range (. 5 ):
        upper_str = chr(random.randint(65,90))
        lower_str = chr(random.randint(97,122))
        random_int = str(random.randint(0,9))
        TEMP_CODE = The random.choice ([upper_str, lower_str, random_int])
        # below to write the image            
img_draw.text ((I + 65 * 45,0), TEMP_CODE, get_random (), font = img_font)
code + = TEMP_CODE Print ( code) # generated random codes stored below the session makes request.session [ ' code ' ] = code img_obj.save(io_obj,'png') return HttpResponse(io_obj.getvalue())

 

Guess you like

Origin www.cnblogs.com/s686zhou/p/11615385.html