How Python makes a simple example of a picture verification code

Source: Internet
Author: User
This article mainly introduced the Python simple production picture Verification code example, has the certain reference value, the interested small partner may refer to

The verification code demonstrated here is simple, and you can distort the character


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:

Pip Install Pillow

Example: Create a picture and fill it with text

#!/usr/bin/python#-*-coding:utf-8-*-from PIL import image, Imagedraw, Imagefont, imagefilter# instance a picture object x 60:width = 60 * 4height = 60# picture Color CLO = (43, 34, 88) # I think it's violet blue image = Image.new (' RGB ', (width, height), clo) # Create Font object: # font files can be used by the operating system, You can also download font = Imagefont.truetype ('./font/arial.ttf ', 36) # Create Draw object: Draw = Imagedraw.draw (image) # output text: str1 = "Ren ren Pyt Hon "W = 4 #距离图片左边距离h = ten #距离图片上边距离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 Picture: {}". Format (Save_dir))
(venv) allenwoo@~/renren/code$ python test2.py saved pictures:./test_code_img.jpg

The picture is as follows:

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


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 PIL import image, Imagedraw, Imagefont, imagefilter# instance a picture object x 60:width = 60 * 4height = 60# picture Color CLO = (43, 34, 88) # I think it's violet blue image = Image.new (' RGB ', (width, height), clo) # Create Font object: # font files can be used by the operating system, You can also download font = Imagefont.truetype ('./font/arial.ttf ', 36) # Create Draw object: Draw = Imagedraw.draw (image) # Fill pixel: # Width every 20, high every 5, form sitting x,y# Red: 220,20,60for x in range (0, width, max): For  y in range (0, height, 5):    Draw.point ((x, y), fill= (220, 20, 60 ) # output text: str1 = "We are Renren" W = 4 #距离图片左边距离h = ten #距离图片上边距离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 Picture: {}". Format (Save_dir))

Result Picture:


PIL 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 UUID Import uuid1from PIL import Image, Imagedraw, Imagefont, Imagefilterimport randomdef Rnd_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 (122) elif i = = 2: # Random lowercase alphabetic decimal ascii an = Random.randint (65, 90)  ELSE: # Random uppercase letters of the decimal ascii an = Random.randint (48, 57) # turns into characters according to ASCII code, return back to Chr (an) # disturbance def Rnd_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, prevent interference characters and captcha character color like # random color 1:def rnd_color (): "' Random color, specify a range:   return: "Return" (Random.randint (255), Random.randint (255), Random.randint (64, 255)) # Random color 2:def rnd_color2 (): "' Random color, specified range: return: ' ' Return (Random.randint (127), Random.randint (+ 127), Random.randint (+, 127)) d EF Create_code (): # 60:width = 4 height = x image = Image.new (' RGB ', (width, height), (192, 192, 192) # Create a Font object: Font = Imagefont.truetype ('./font/arial.ttf ', 36) # Create Draw object: Draw = Imagedraw.draw (image) # Fill each pixel: for x in range (0, width, max): for y in range (0, height, ten): Draw.point ((x, y), Fill=rnd_color ()) # Fill Filling character _str = "" # Fill in 4 random numbers or letters as CAPTCHA for T in range (4): c = Rnd_char () _str = "{} {}". Format (_str, c) # random distance image top height , 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 void 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 code {} to database". Format (_STR)) # Add character interference to the image, intensity W, H Control for J in range (0, Width, +): dis = Rnd_dis () w = t * + J # random distance picture top height, but at least 30 pixels from h = random.randint (1, height-30) Draw.text ((W, h), Dis, Font=font, Fill=rndcolor ()) # Blur: Image.filter (imagefilter.blur) # UUID1 generate only A string as the captcha picture name Code_name = ' {}.jpg '. Format (UUID1 ()) Save_dir = './{} '. Format (code_name) image.save (save_dir, ' jpeg ') p Rint ("Saved Picture: {}". Format (SAVE_DIR) # When running the file directly and, run the following code if NAME = = "Main": Create_code () 
(venv) allenwoo@~/renren/code$ python test.py save captcha ef3k to database saved Picture:./c86e03c0-1c23-11e7-999d-f45c89c09e61.jpg (VENV) allenwoo@~/renren/code$ python test.py save captcha i37x to database saved Picture:./cb8aed02-1c23-11e7-9b18-f45c89c09e61.jpg (VENV) allenwoo@~/renren/code$ python test.py save captcha vVL1 to database saved Picture:./cc120da8-1c23-11e7-b762-f45c89c09e61.jpg (VENV) allenwoo@~/renren/code$ python test.py save captcha k6w3 to database saved Picture:./cc891e05-1c23-11e7-b7ec-f45c89c09e61.jpg




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

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.