Python simple to make image verification code

Source: Internet
Author: User

-Everyone can learn python--
The verification code demonstrated here is simple, and you can distort the character


Everyone can learn Python.png

Python third-party library is incredibly powerful, PIL is a Python d third-party image processing module, we can also use it to generate image verification code
PIL installation
Command installation:

install pillow

Download Source Installation:
Copy Address: Https://github.com/python-pillow/Pillow

PiL use

Example: Create a picture and fill it with text

#!/usr/bin/python#-*-coding:utf-8-*-from PILImport Image, Imagedraw, Imagefont, ImageFilter# instance one Picture object x 60:width =60 *4Height =60# Picture ColorCLO = (43,34,88)# I think it's Violet Blue #Image = Image.new (' RGB ', (width, height), CLO)# Create a Font object:# font files can be used by the operating system, or can be downloaded online font = Imagefont.truetype ('./font/ Arial.ttf ', 36) # Create Draw object: draw = Imagedraw.draw (image) # output text: str1 =  " ren ren Python "w = 4  #距离图片左边距离 h = 10  #距离图片上边距离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 pictures: {}". Format (save_dir))    
(venv) [email protected]~/renren/code$ python test2.py 已保存图片: ./test_code_img.jpg

The picture is as follows:


Paste_image.png

There is no color in the text, we can also add color, only need to be in the text of the fill parameter.
Draw.text ((W, h), str1, font=font, fill = (78, 64, 65))
Whatever color you want to add


Paste_image.png

We can also make the background into a lot of small dots, every n pixels filled with other colors such as:

#!/usr/bin/python#-*-coding:utf-8-*-from PILImport Image, Imagedraw, Imagefont, ImageFilter# instance one Picture object x 60:width =60 *4Height =60# Picture ColorCLO = (43,34,88)# I think it's Violet Blue #Image = Image.new (' RGB ', (width, height), CLO)# Create a Font object:# font files can be used by the operating system, or can be downloaded onlineFont = Imagefont.truetype ('./font/arial.ttf ',36)# Create Draw object:Draw = Imagedraw.draw (image)# Fill pixel:# width Every 20, high every 5, form coordinates x, y# Red: 220,20,60for xIn range (0, Width,): For YIn range (0, Height,5): Draw.point ((x, y),fill= (UP, 20, 60)) # output text: str1 = " we are Renren " w = 4  #距离图片左边距离 h = 10  #距离图片上边距离draw. Text ((w, h), str1 , font=font, fill = (78, 64, 65)) # Blur: Image.filter (ImageFilter.BLUR) Span class= "hljs-attr" >code_name = ' test_code_img.jpg ' save_dir = './{} '. Format (code_name) Image.Save (Save_dir, ' jpeg ') print ( "Saved pictures: {}". Format (save_dir))     

Result Picture:


Paste_image.pngpil Making Verification Code

Using these, and the random generators we learned before, we can do a verification code,
Generate code codes for verification codes

#!/usr/bin/python#-*-coding:utf-8-*-From UUIDImport Uuid1From PILImport Image, Imagedraw, Imagefont, ImageFilterImport RandomDefRnd_char():"' Random one letter or number: return: '# random one letter or number i = Random.randint (1,3)if i = =1:# random number of decimal ascii an = Random.randint (97,122)elif i = =2:# Random Lowercase alphabetic decimal ascii an = Random.randint (65,70gElse# Random uppercase letters in decimal ascii an = Random.randint (48,57)# turn to character according to ASCII code, return backReturn Chr (AN)# interferenceDefRnd_dis():"' Random One Noise word: return: ' d = [' ^ ',‘-‘,' ~ ',‘_‘,‘.‘] i = Random.randint (0, Len (d)-1)return D[i]# Two random colors are defined in different areas to prevent the same interference characters and captcha character color# Random Color 1:DefRnd_color():"' Random color, specified range: return: 'Return (Random.randint (64,255), Random.randint (64,255), Random.randint (64,255))# Random Color 2:DefRnd_color2():"' Random color, specified range: return: 'Return (Random.randint (32,127), Random.randint (32,127), Random.randint (32,127))DefCreate_code():# x 60:width =60 *4 height =Image = Image.new (' RGB ', (width, height), (192,192,192))# Create a Font object: Font = Imagefont.truetype ('./font/arial.ttf ',66L# Create Draw object: Draw = Imagedraw.draw (image)# Populate each pixel:For XIn range (0, Width,20):For YIn range (0, Height,Ten): Draw.point ((x, y), Fill=rnd_color ())# fill Character _str =""# Fill in 4 random numbers or letters as a verification codeFor TIn range (4): c = Rnd_char () _str ="{} {}". Format (_STR, C)# random distance from the top height of the picture, but at least 30 pixels from h = random.randint (1, Height-30)# width, each character occupies a picture width of 1/4, plus 10 pixels in the gap W = width/4 * t +Draw.text ((W, h), C, Font=font, Fill=rnd_color2 ())# in the actual project, the verification code will be saved in the database, plus the Time field print ("Save Captcha {} to database". Format (_STR))# Add character interference to the picture, density is controlled by W, Hfor J in range (0, width, 30): Dis = Rnd_dis () w = t * 15 + J # random distance picture top height, but at least distance 30 pixels h = random.randint (1, height-30) Draw.text ((W, h), Dis, font= Font, Fill=rndcolor ()) # Blur: Image.filter (Imagefilter.blur) # UUID1 generates a unique string as the captcha picture name code_name =  ' {}.jpg '. Format (UUID1 ()) Save_dir =  ' jpeg ') print (" saved Picture: {} ". Format (save_dir)) # when directly running the file is and, run the following code if __name__ =  "__main__": Create_code ()     
(venv) [Email protected]~/renren/code$ python test.py Save Verification Code EF3k to database saved pictures:./C86e03C0-1C23-11e7-999d-f45C89C09e61.jpg (venv) [email protected]~/renren/code$ python test.py Save Verification Code I37X to database saved pictures:./CB8aed02-1C23-11e7-9b18-f45C89C09e61.jpg (venv) [email protected]~/renren/code$ python test.py Save Verification Code VVL1 Save picture to database:./Cc120da8-1c 23-11e7-b762-f45 c89c 09e61.jpg (venv) [email protected]~/renren/code$ python test.py Save verification Code K6w3 to database saved pictures:./cc891e05 -1c23 -11e7-b7ec-f45c 89c09e61.jpg    

Paste_image.png
Paste_image.png
Paste_image.png
Paste_image.png

Do you think it's hard? Finally, there are some logic problems in the code of generating captcha to understand

You are welcome to join the Learning Exchange Group if you encounter any problems or want to acquire learning resources in the learning process.
343599877, we learn the front-end together!

Python simple to make image verification code

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.