How to generate a verification code instance using Python

Source: Internet
Author: User
Verification codes are often used in web development. in order to prevent robot registration or malicious login and query, the function cannot be underestimated. However, the verification code is not implemented by a function and needs to generate a graph... verification codes are often used in web development. in order to prevent robot registration or malicious login and query, the function cannot be underestimated.

However, the verification code is not a function. it requires generating images and watermarks. In fact, each language has related functions to generate image and text watermarks. Including php, which I am familiar with. today I will mainly share how to use python to generate verification codes.

Python uses the following modules to generate verification codes: Image, ImageDraw, ImageFont, ImageFilter, and Random number generation module Random.

The code is as follows:

#! /Usr/bin/env python # coding = utf-8import randomimport Image, ImageDraw, ImageFont, ImageFilter _ letter_cases = "abcdefghjkmnpqrstuvwxy" # lowercase letters, removing possible interference with I, l, o, z_upper_cases = _ letter_cases.upper () # uppercase letter _ numbers = ''. join (map (str, range (3, 10) # number init_chars = ''. join (_ letter_cases, _ upper_cases, _ numbers) fontType = "/usr/share/fonts/truetype/freefont/FreeSans. ttf "def create_validate_code (size = (120, 30), chars = init_chars, img_type =" GIF ", mode =" RGB ", bg_color = (255,255,255), fg_color = (0, (0,255), font_size = 18, font_type = fontType, length = 4, draw_lines = True, n_line = (1, 2), draw_points = True, point_chance = 2 ): ''' @ todo: generate the verification code Image @ param size: image size, format (width, height), default value: (120, 30) @ param chars: Allowed character set combination, format string @ param img_type: the format in which the image is saved. the default value is GIF. optional values include GIF, JPEG, TIFF, and PNG @ param mode. the default value is RGB @ param bg_color: background color. the default value is white @ param fg_color: foreground color, verification code character color. the default value is Blue # 0000FF @ param font_size: verification code font size @ param font_type: verification code font, the default value is AE _AlArabiya.ttf @ param length: number of characters in the verification code @ param draw_lines: whether to draw interference lines @ param n_lines: the number range of interference lines. format tuples. the default value is (1, 2 ), valid only when draw_lines is True @ param draw_points: whether to draw interference points @ param point_chance: the probability of occurrence of interference points. The value range is [0,100] @ return: [0]: PIL Image instance @ return: [1]: string '''width, height = size # width, height img = Image in the verification code Image. new (mode, size, bg_color) # create a graphic draw = ImageDraw. draw (img) # Create a paint brush if draw_lines: create_lines (draw, n_line, width, height) if draw_points: create_points (draw, point_chance, width, height) strs = create_strs (draw, chars, length, font_type, font_size, width, height, fg_color) # Image distortion parameter params = [1-float (random. randint (1, 2)/100, 0, 0, 0, 1-float (random. randint (1, 10)/100, float (random. randint (1, 2)/500, 0.001, float (random. randint (1, 2)/500] img = img. transform (size, Image. PERSPECTIVE, params) # create distortion img = img. filter (ImageFilter. EDGE_ENHANCE_MORE) # Filter, boundary enhancement (greater threshold) return img, strs def create_lines (draw, n_line, width, height): '''draw interference line''' line_num = random. randint (n_line [0], n_line [1]) # Number of interfering lines for I in range (line_num): # starting point begin = (random. randint (0, width), random. randint (0, height) # end point end = (random. randint (0, width), random. randint (0, height) draw. line ([begin, end], fill = (0, 0, 0) def create_points (draw, point_chance, width, height ): '''plot interference point' ''chance = min (100, max (0, int (point_chance) # The size is limited to [0,100] for w in xrange (width ): for h in xrange (height): tmp = random. randint (0,100) if tmp> 100-chance: draw. point (w, h), fill = (0, 0, 0) def create_strs (draw, chars, length, font_type, font_size, width, height, fg_color ): '''plot the verification code character ''' to generate a string of the given length. the returned list format is '''c_chars = random. sample (chars, length) strs = '% s' % ''. join (c_chars) # Separate each character with spaces. font = ImageFont. truetype (font_type, font_size) font_width, font_height = font. getsize (strs) draw. text (width-font_width)/3, (height-font_height)/3), strs, font = font, fill = fg_color) return ''. join (c_chars) if _ name _ = "_ main _": code_img = create_validate_code () code_img [0]. save ("validate.gif", "GIF") print code_img [1]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.