Organize Python to generate random Chinese image verification code source code

Source: Internet
Author: User
Tags drawtext

When logging on to many websites, they no longer use simple English and digital verification codes. In order to prevent attacks by disgusting registration and group-sending software, they are now using Chinese verification codes.

Today, we will share with you the source code of a random Chinese verification code image generated using Python.

 

The code is as follows: Copy code

#-*-Coding: UTF-8 -*-
Import Image, ImageDraw, ImageFont
Import random
Import math, string

Class RandomChar ():
"Used to randomly generate Chinese characters """
@ Staticmethod
Def Unicode ():
Val = random. randint (0x4E00, 0x9FBF)
Return unichr (val)

@ Staticmethod
Def GB2312 ():
Head = random. randint (0xB0, 0xCF)
Body = random. randint (0xA, 0xF)
Tail = random. randint (0, 0xF)
Val = (head <8) | (body <4) | tail
Str = "% x" % val
Return str. decode ('Hex'). decode ('gb2312 ')

Class ImageChar ():
Def _ init _ (self, fontColor = (0, 0, 0 ),
Size = (100, 40 ),
FontPath = 'wqy. ttc ',
BgColor = (1, 255,255,255 ),
FontSize = 20 ):
Self. size = size
Self. fontPath = fontPath
Self. bgColor = bgColor
Self. fontSize = fontSize
Self. fontColor = fontColor
Self. font = ImageFont. truetype (self. fontPath, self. fontSize)
Self. image = Image. new ('rgb ', size, bgColor)

Def rotate (self ):
Self. image. rotate (random. randint (0, 30), expand = 0)

Def drawText (self, pos, txt, fill ):
Draw = ImageDraw. Draw (self. image)
Draw. text (pos, txt, font = self. font, fill = fill)
Del draw

Def randRGB (self ):
Return (random. randint (0,255 ),
Random. randint (0,255 ),
Random. randint (0,255 ))

Def randPoint (self ):
(Width, height) = self. size
Return (random. randint (0, width), random. randint (0, height ))

Def randLine (self, num ):
Draw = ImageDraw. Draw (self. image)
For I in range (0, num ):
Draw. line ([self. randPoint (), self. randPoint ()], self. randRGB ())
Del draw

Def randChinese (self, num ):
Gap = 5
Start = 0
For I in range (0, num ):
Char = RandomChar (). GB2312 ()
X = start + self. fontSize * I + random. randint (0, gap) + gap * I
Self. drawText (x, random. randint (-5, 5), RandomChar (). GB2312 (), self. randRGB ())
Self. rotate ()
Self. randLine (18)

Def save (self, path ):
Self. image. save (path)

 

Generate a verification code using python (complete webpy verification code class)

Python can generate verification codes using mature wheezy. captcha. First install the PIL package easy_install PIL, and then install wheezy. captcha easy_install wheezy. captcha.

It is easy to generate a verification code after installation:

 

The code is as follows: Copy code

Captcha_image_t = captcha (drawings = [
Background (),
Text (fonts = [
Path. join (_ fontsDir, '2017 ___. Ttf '),
Path. join (_ fontsDir, 'andyb. Ttf')],
Drawings = [
Warp (),
Rotate (),
Offset ()
]),
Curve (),
Noise (),
Smooth ()
])
Chars_t = random. sample (_ chars, 4)

Image_t = captcha_image_t (chars_t)
Image_t.save('test.jpeg ', 'jpeg', quality = 75)

 

The verification code diagram is as follows:

Captcha

The implementation of the complete webpy verification code generation class is as follows:

 

The code is as follows: Copy code

#! /Usr/bin/env python
# Coding: UTF-8

_ Author _ = 'outofmemory. Cn'

From wheezy. captcha. image import captcha

From wheezy. captcha. image import background
From wheezy. captcha. image import curve
From wheezy. captcha. image import noise
From wheezy. captcha. image import smooth
From wheezy. captcha. image import text

From wheezy. captcha. image import offset
From wheezy. captcha. image import rotate
From wheezy. captcha. image import warp

Import random
Import web

From OS import path
Try:
From cStringIO import StringIO
Except t:
From StringIO import StringIO

If _ name _ = '_ main __':
Import OS, sys
WebPath = OS. path. dirname (OS. path. dirname (OS. path. abspath (_ file __)))
Sys. path. insert (0, webPath)

From run import session

_ ControllersDir = path. abspath (path. dirname (_ file __))
_ WebDir = path. dirname (_ controllersDir)
_ FontsDir = path. join (path. dirname (_ webDir), 'fonts ')

_ Chars = 'abcdefjhjklmnpqrstuvwxy3456789'

SESSION_KEY_CAPTCHA = 'captcha'

Def isValidCaptcha (captchaInputName = 'captcha '):
UserInputVal = web. input (). get (captchaInputName)
If not userInputVal: return False
CorrectVal = session [SESSION_KEY_CAPTCHA]
Return userInputVal. upper () = correctVal

Class Captcha:
'''Verification code '''

Def GET (self ):
Captcha_image = captcha (drawings = [
Background (),
Text (fonts = [
Path. join (_ fontsDir, '2017 ___. Ttf '),
Path. join (_ fontsDir, 'andyb. Ttf')],
Drawings = [
Warp (),
Rotate (),
Offset ()
]),
Curve (),
Noise (),
Smooth ()
])
Chars = random. sample (_ chars, 4)
Session [SESSION_KEY_CAPTCHA] = ''. join (chars)
Image = captcha_image (chars)
Out = StringIO ()
Image. save (out, "jpeg", quality = 75)
Web. header ('content-type', 'image/jpeg ')
Return out. getvalue ()

If _ name _ = '_ main __':
Print _ fontsDir
Captcha_image_t = captcha (drawings = [
Background (),
Text (fonts = [
Path. join (_ fontsDir, '2017 ___. Ttf '),
Path. join (_ fontsDir, 'andyb. Ttf')],
Drawings = [
Warp (),
Rotate (),
Offset ()
]),
Curve (),
Noise (),
Smooth ()
])
Chars_t = random. sample (_ chars, 4)

Image_t = captcha_image_t (chars_t)
Image_t.save('test.jpeg ', 'jpeg', quality = 75)

 

The font files used in the program should be placed under the fonts directory of the same level in the web directory. The Two font files in the program are copies of the windows font, which can be used normally in linux. Pay attention to the case of the extension.

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.