Python uses the PIL library to implement the verification code image method,

Source: Internet
Author: User

Python uses the PIL library to implement the verification code image method,

This example describes how Python uses the PIL library to implement the verification code image. We will share this with you for your reference. The details are as follows:

Currently, image verification codes are a common method to prevent robots from submitting forms on webpages. I will not describe it in detail here. I believe you have met it.

Now we provide the code to use Python PIL library to implement the verification code image. Detailed comments are provided in the Code.

#! /Usr/bin/env python # coding = utf-8import randomfrom PIL import Image, ImageDraw, ImageFont, ImageFilter_letter_cases = "abcdefghjkmnpqrstuvwxy" # lowercase letters, removing potentially interfering 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) 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 = "AE _AlArabiya.ttf", length = 4, draw_lines = True, n_line = (1, 2 ), draw_points = True, point_chance = 2): ''' @ todo: generate the verification code image @ param size: The image size, format (width, height), default value (120, 30) @ param chars: allowed character set combination. Format String @ param img_type: The image storage format. The default value is GIF. The optional values are GIF, JPEG, TIFF, and PNG @ param mode: image 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: The Verification Code font. Default Value: AE _AlArabiya.ttf @ param length: Number of Verification Code characters @ param draw_lines: Indicates whether to draw interference lines @ param n_lines: the number 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 interference points, size Range: [0,100] @ return: [0]: PIL Image instance @ return: [1]: character string '''width, height = size # width, high img = Image. new (mode, size, bg_color) # create a graphic draw = ImageDraw. draw (img) # create a brush def get_chars (): ''' to generate a string of the given length, and return the List format ''' return random. sample (chars, length) def create_lines (): ''' draw interference line''' line_num = random. randint (* n_line) # Number of interfering lines for I in range (line_num): # Starting Point begin = (random. randint (0, size [0]), random. randint (0, size [1]) # end Point end = (random. randint (0, size [0]), random. randint (0, size [1]) draw. line ([begin, end], fill = (0, 0, 0) def create_points (): '''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 Verification Code character ''' c_chars = get_chars () 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 draw_lines: create_lines () if draw_points: create_points () strs = create_strs () # graphic 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, strsif _ name _ = "_ main _": code_img = create_validate_code () code_img.save ("validate.gif", "GIF ")

The final result returns a tuples. The first returned value is an Image instance, and the second parameter is a string in the Image (whether the comparison is correct ).

The final result returns a tuples. The first returned value is an Image instance, and the second parameter is a string in the Image (whether the comparison is correct ).

Note that if an IOError is thrown when an ImageFont. truetype instance is generated, it may be that the computer running the Code does not contain the specified font and needs to be downloaded and installed.

Verification Code image:

At this time, careful students may ask, if every time you generate a verification code, you must first save the generated image and then display it on the page. This is unacceptable. At this time, we need to use the python built-in StringIO module, which has behavior similar to the file object, but it operates on memory files. So we can write the code like this:

try:  import cStringIO as StringIOexcept ImportError:  import StringIOmstream = StringIO.StringIO()img = create_validate_code()[0]img.save(mstream, "GIF") 

In this way, you only need to use "mstream. getvalue ()" to output the image. For example, in Django, we first define a url like this:

from django.conf.urls.defaults import *urlpatterns = patterns('example.views',  url(r'^validate/$', 'validate', name='validate'),)

In views, we store the correct string in the session, so that when you submit a form, you can compare it with the correct string in the session.

from django.shortcuts import HttpResponsefrom validate import create_validate_codedef validate(request):  mstream = StringIO.StringIO()  validate_code = create_validate_code()  img = validate_code[0]  img.save(mstream, "GIF")  request.session['validate'] = validate_code[1]  return HttpResponse(mstream.getvalue(), "image/gif")

I hope this article will help you with Python programming.

Articles you may be interested in:
  • Tutorial on batch adding serial numbers to images using the PIL library in Python
  • Python uses the PIL library to implement image Gaussian Blur instances
  • Python PIL module and randomly generated Chinese Verification Code
  • Python generates Verification Code Image Code sharing
  • Detailed explanation of Python verification code recognition
  • Python website verification code recognition
  • Send and obtain SMS verification Codes Using python
  • Python verification code identification and processing instance
  • Python Verification Code Recognition Method
  • Python generates Verification Code instances

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.