Pillow Instances | Generate Random Verification code

Source: Internet
Author: User

1 PIL (Python Image Library)

PIL is a basic image processing package for Python, which includes cutting, zooming, writing, and other functions of various pieces. Now, I'll take the example of generating a random verification code to tell the basic usage of PIL.

PiL Library seems to have been abandoned, just for the update, the last time you use the show () directly to the picture, in the system default Picture Manager open. Fortunately pillow, a PiL dialect, will PIL continue to maintain the continued.

Generating verification code generally requires a series of operations such as rotation, twisting, and discoloration of the written text to avoid the recognition of computer algorithms.

Therefore, it is a good choice to define a class that generates a verification code, rotating, twisting, and changing colors as a series of methods for this class.

2 Initializing the Captcha class

CAPTCHA is the abbreviation for completely automated public Turing test to tell Computers and humans Apart (fully automated computer and human Turing Test), the most famous Captcha project in the world, after To be fed up with Google, and now they're starting to differentiate people and computers in ways other than pictures

Initialization needs to set the size of the captcha picture, and the size of the font, by default, the appropriate value has been selected.

You need to use the new method of the draw sub-package to create a new picture, given mode, size, and color. It's like a curtain in a real painting.

mode is related to different image representation formats,

Color pictures can be synthesized by red R, Green G, blue b Three primary colors, stored in the computer is the 3 matrix, the most common mode is called ' RGB ';

Black and white pictures only need a layer, with ' 1 ' expression;

The color picture displayed on the computer screen on the basis of the three primary colors, and then a transparent layer, showing how many next layer of images can be through, this mode is called ' RGBA ', a generation of alpha.

From PIL import Image

Class Captcha (object): def __init__ (self,size= (100,40), fontsize=30): Self.font = Imagefont.truetype (' \ c \ Windows\fonts\arial.ttf ', fontSize) self.size = size self.image = image.new (' RGBA ', self.size, (255,) *) Self.texts = Self.randnum (5)

The Imagefont package is used to work with fonts, requires a specific path to use the font, and the size of the font, and the word under the Windows system is under the C:\Windows\Fonts\ path.

3 Generate random numbers and colors

Random numbers

Using the Randint (Start,end) method of the random package, a number in the 0~9 is randomly generated, and it is important to note that it contains the start and end

    def randnum (self,bits):        return ". Join (Str (random.randint (0,9)) for I in range (bits))

Random Color

Color is generally used in 8-bit notation, the decimal is an integer 0~255, randomly generated a ternary group can be

    def randcolor (self):        Self.fontcolor = (Random.randint (0,250), Random.randint (0,250), Random.randint (0,250))

It's all very simple.

4 Write text

Writing text requires a Imagedraw package

    def write (self,text,x):        draw = Imagedraw.draw (self.image)        Draw.text ((x,4), text,fill=self.fontcolor,font= Self.font)

The text method needs to specify, where to write the text, the origin in the upper-left corner, of course in pixels, the text to write, the color to write the text, and the last word font

5 Rotate Text

Rotation is generally not the direct rotation of the text, but the rotation of the curtain, where a random rotation of an angle is required.

Rotating the curtain will create a problem, the rotation behind the corner will reach the outside of the artboard, and finally we need a square captcha image.

The curtains stretched out to the outside of the artboard need to be trimmed off, as the rotating space needs to be mended.

Image.composite (IMG1,IMG2,IMG1) can solve this problem, it will img1 transparent/blank place, with Img2 fill up. It should be a white background here.

    def rotate (self):        rot = Self.image.rotate (Random.randint ( -10,10), expand=0) #默认为0, which represents clipping out of the outer part of the artboard        FFF = Image.new (' RGBA ', rot.size, (255,))        self.image = Image.composite (Rot,fff,rot)

6 form the Verification code

With the above method to pave the way, at a certain interval, write a few numbers, you get the verification code

    def writenum (self):        x =        Xplus = Ten        for text in self.texts:            self.randcolor ()            self.write (text, x)            self.rotate ()            x + = Xplus        return self.texts

This method returns the text of the verification code so that the computer can determine if the person entered correctly. Unlike several of the methods above, this approach is user-oriented.

The end result is this.

Attached: Complete code

Class Captcha (object): Def __init__ (Self,size= (100,40), fontsize=30): Self.font = Imagefont.truetype (' C:\Windows\ Fonts\arial.ttf ', fontSize) self.size = Size Self.image = image.new (' RGBA ', self.size, (255,) *) Self.te XTS = Self.randnum (5) def rotate (self): rot = Self.image.rotate (Random.randint ( -10,10), expand=0) FFF = Im Age.new (' RGBA ', rot.size, (255), Self.image = Image.composite (Rot,fff,rot) def randcolor (self): Self.fon TColor = (Random.randint (0,250), Random.randint (0,250), Random.randint (0,250)) def randnum (self,bits): Return '. J        Oin (str (random.randint (0,9)) for I (BITS)) def write (self,text,x): Draw = Imagedraw.draw (self.image)        Draw.text ((x,4), Text,fill=self.fontcolor,font=self.font) def writenum (self): x = ten Xplus = 15 For text in Self.texts:self.randColor () self.write (text, x) self.rotate () x + = Xplus return sElf.texts def Save (self): Self.image.save (' captcha.jpg ') img = captcha () num = Img.writenum () #img. image.sh ow () #img. Save ()

Pillow Instances | Generate Random Verification code

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.