A tutorial for writing scripts that generate CAPTCHA code in Python

Source: Internet
Author: User
In web development often use verification code, in order to prevent the registration of robots or malicious login and query, etc., the role should not be underestimated

But the verification code is not a function can be done, it needs to generate images and watermarks, in fact, each language has related functions to generate images and text watermark. Including my familiar PHP, hehe, today mainly to share how to use Python to generate verification code.

Python generated verification code is mainly used in the following modules: 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 potentially disturbing i,l,o,z_upper_cases = _letter_cases.upper () # uppercase letters _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= (+), Chars=init_chars, img_type=" GI F ", mode=" RGB ", bg_color= (255, 255, 255), fg_color= (0, 0, 255), FO Nt_size=18, Font_type=fonttype, length=4, Draw_lines=true, n_line= (1, 2), draw_points=true, point_chance = 2): "@todo: Generate CAPTCHA image @param size: size of picture, format (wide, high), default to (+) @param chars: Allowed character set, format string @param img_type: Picture saved format, default GIF, optional gif,jpeg,tiff,png @param mode: Picture, default RGB @par AM Bg_color: Background color, default is white @param fg_color: foreground, validateCode character color, default is blue #0000ff @param font_size: captcha font size @param font_type: captcha font, default to Ae_alarabiya.ttf @param length: Number of captcha characters @param Dr Aw_lines: Whether the interference line is crossed @param n_lines: The number range of the interference line, the format tuple, the default is (1, 2), only valid when Draw_lines is true @param draw_points: whether to draw the interference point @param point_ Chance: Probability of occurrence of interference points, size range [0] @return: [0]: PIL image instance @return: [1]: Captcha image in the string ' width, height = size # wide, high img = Im Age.new (mode, size, bg_color) # Create graphic draw = Imagedraw.draw (img) # Create brush if Draw_lines:create_lines (Draw,n_line,width,heig HT) if Draw_points:create_points (draw,point_chance,width,height) STRs = Create_strs (Draw,chars,length,font_type,  Font_size,width,height,fg_color) # Graphics Twist parameter params = [1-float (Random.randint (1, 2))/100, 0, 0, 0, 1 -Float (random.randint (1))/, Float (random.randint (1, 2))/, 0.001, float (random.randint (1, 2) )/+] img = img.transform (size, image.perspective, params) # Create twist img = Img.filter (imagefilter.edge_enhance_more # Filter, Edge Enhancement (threshold value) 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): # start point begin = (Random.randint (0, width), random.randint (0, height)) #结束点 end = (Random.randint (0, wid TH), random.randint (0, height)) draw.line ([begin, end], fill= (0, 0, 0)) def create_points (Draw,point_chance,width, Height): ' Draw disturbance point ' ' Chance = min (max (0, Int (point_chance))) # size limit at [0, +] for W in xrange (width): for h in Xran GE (height): tmp = Random.randint (0, +) if tmp > 100-chance:draw.point ((w, h), fill= (0, 0, 0)) def Create_st RS (Draw,chars,length,font_type, Font_size,width,height,fg_color): ' Draw captcha character ' ' to generate string of a given length, return list format ' C_chars = Random.sample (chars, length) STRs = '%s '% '. Join (C_chars) # Each character is separated by a space before and after the font = Imagefont.truetype (Font_type, font_s ize) 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") prin T Code_img[1]
  • Related Article

    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.