Joke Collection Website - Public benefit messages - Find python algorithm to generate verification code as shown in the figure.

Find python algorithm to generate verification code as shown in the figure.

Def gene _ text ():

Source = list (string. letter)

For indexes in the range (0, 10):

source.append(str(index))

Return "". Join (random. Sample (source, number)) # NUMBER is the number of digits to generate the verification code.

Then we need to create a picture and write it into a string. It should be noted that the fonts inside depend on different systems. If you can't find the system font path, you can set it.

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) # Font and font size of verification code

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

Next, we will draw some interference lines on the picture.

# Used to draw interference lines

Define gene lines (drawing, 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)

Finally, create a twist and add a filter to enhance the effect of the verification code.

Image = Image.transform ((width +20, height+10), image.affine, (1, -0.3, 0, -0. 1, 0), image.bilinear) # Create a distortion.

Image = image.filter (imagefilter.edge _ enhancement _ more) # filter, boundary enhancement.

Image.save('idencode.png') # Save the verification code picture.