Python allows you to easily create image verification codes,

Source: Internet
Author: User

Python allows you to easily create image verification codes,

-Everyone can learn Python --
The verification codes demonstrated here are simple. You can also distort the characters.


You can learn python.png

The Python third-party library is extremely powerful. PIL is a python d third-party image processing module. We can also use it to generate image verification codes.
PIL Installation
Command installation:

pip install pillow

Download the source code for installation:
Copy address: https://github.com/python-pillow/Pillow

PIL usage

Example: generate an image and fill it with text

#! /Usr/bin/python #-*-coding: UTF-8-*-from PIL import Image, ImageDraw, ImageFont, ImageFilter # instance: an Image object 240x60: width = 60*4 height = 60 # image color clo = (43, 34, 88) # I think it is purple-blue Image = image. new ('rgb ', (width, height), clo) # create a Font object: # font files can be downloaded using the operating system or from the Internet. truetype ('. /font/Arial. ttf', 36) # create a Draw object: draw = ImageDraw. draw (image) # output text: str1 = "ren Python" w = 4 # distance from the left of the image to h = 10 # distance from the top of the image to draw. text (w, h), str1, font = font) # blur: image. filter (ImageFilter. BLUR) code_name = 'test_code_img.jpg 'Save _ dir = '. /{}'. format (code_name) image. save (save_dir, 'jpeg ') print ("saved image :{}". format (save_dir ))
(Venv) allenwoo @~ /Renren/code $ python test2.py saved image:./test_code_img.jpg

The image is as follows:


Paste_Image.png

There is no color in the text. We can also add a color, just pass the fill parameter in the text.
Draw. text (w, h), str1, font = font, fill = (78, 64, 65 ))
Random color


Paste_Image.png

We can also make the background into many smaller points, and fill in other colors at intervals of n pixels, for example:

#! /Usr/bin/python #-*-coding: UTF-8-*-from PIL import Image, ImageDraw, ImageFont, ImageFilter # instance: an Image object 240x60: width = 60*4 height = 60 # image color clo = (43, 34, 88) # I think it is purple-blue Image = image. new ('rgb ', (width, height), clo) # create a Font object: # font files can be downloaded using the operating system or from the Internet. truetype ('. /font/Arial. ttf', 36) # create a Draw object: draw = ImageDraw. draw (image) # Fill pixel: # width every 20, height every 5, form coordinates x, y # Red:, 60for x in range (0, width, 20 ): for y in range (0, height, 5): draw. point (x, y), fill = (220, 20, 60) # output text: str1 = "we are renren" w = 4 # distance from the left of the image to h = 10 # distance from the top of the image to draw. text (w, h), str1, font = font, fill = (78, 64, 65) # blur: image. filter (ImageFilter. BLUR) code_name = 'test_code_img.jpg 'Save _ dir = '. /{}'. format (code_name) image. save (save_dir, 'jpeg ') print ("saved image :{}". format (save_dir ))

Result image:


Paste_Image.pngPIL

Using the above, and the random generator random we have learned before, we can create a verification code,
Generate Verification Code

#! /Usr/bin/python #-*-coding: UTF-8-*-from uuid import uuid1from PIL import Image, ImageDraw, ImageFont, ImageFilterimport randomdef rnd_char (): '''random letter or number: return: ''' # random letter or number I = random. randint (1, 3) if I = 1: # random digit ASCII Code an = random. randint (97,122) elif I = 2: # random lowercase letter ASCII Code an = random. randint (65, 90) else: # random uppercase letter ASCII Code an = random. randint (48, 57) # convert Ascii code into characters and return Return chr (an) # interference def rnd_dis (): ''' random disturbance word: return: ''' d = ['^ ','-','~ ','_','. '] I = random. randint (0, len (d)-1) return d [I] # two random colors specify different regions to prevent interference characters from being the same color as the verification code characters # random color 1: def rnd_color (): ''' random color, specified range: return: ''' return (random. randint (64,255), random. randint (64,255), random. randint (64,255) # random color 2: def rnd_color2 (): ''' random color, specified range: return: ''' return (random. randint (32,127), random. randint (32,127), random. randint (32,127) def create_code (): #240x60: width = 60*4 height = 60 image = Image. new ('rgb ', (width, height), (192,192,192) # create a Font object: font = ImageFont. truetype ('. /font/Arial. ttf', 36) # create a Draw object: draw = ImageDraw. draw (image) # Fill in each pixel: for x in range (0, width, 20): for y in range (0, height, 10): draw. point (x, y), fill = rnd_color () # fill in the character _ str = "" # fill in four random numbers or letters as the verification code for t in range (4): c = rnd_char () _ str = "{}{}". format (_ str, c) # random distance from the top of the image, but at least 30 pixels h = random. randint (1, height-30) # width. Each character occupies 1/4 of the image width, and a 10 pixel gap w = width/4 * t + 10 draw is added. text (w, h), c, font = font, fill = rnd_color2 () # in the actual project, the verification code is saved in the database, add the time field print ("Save the verification code {} to the Database ". format (_ str) # Add a character disturbance to the image. The density is controlled by w and h for j in range (0, width, 30): dis = rnd_dis () w = t * 15 + j # random distance from the top of the image, but at least 30 pixels h = random. randint (1, height-30) draw. text (w, h), dis, font = font, fill = rndColor () # Fuzzy: image. filter (ImageFilter. BLUR) # uuid1 generates a unique string as the verification code image name code_name = '00000000.jpg '. format (uuid1 () save_dir = '. /{}'. format (code_name) image. save (save_dir, 'jpeg ') print ("saved image :{}". format (save_dir) # When directly running the file is sum, run the following code: if _ name _ = "_ main _": create_code ()
(Venv) allenwoo @~ /Renren/code $ python test. py Save the verification code ef3k to the database saved picture:./c86e03c0-1c23-11e7-999d-f45c89c09e61.jpg (venv) allenwoo @~ /Renren/code $ python test. py Save the verification code I37X to the database saved picture:./cb8aed02-1c23-11e7-9b18-f45c89c09e61.jpg (venv) allenwoo @~ /Renren/code $ python test. py Save the verification code vVL1 to the database saved picture:./cc120da8-1c23-11e7-b762-f45c89c09e61.jpg (venv) allenwoo @~ /Renren/code $ python test. py Save the verification code K6w3 to the database saved picture:./cc891e05-1c23-11e7-b7ec-f45c89c09e61.jpg

Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png

What do you think is difficult? Finally, we need to understand some logic problems in the Code for generating the verification code.

If you have any questions during the learning process or want to obtain learning resources, join the learning exchange group.
626062078. Let's learn Python together!

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.