Python simple to make image verification code

Source: Internet
Author: User
Tags image filter uppercase letter
-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:

Pip Install Pillow

Download Source Installation:
Copy address:

PiL use

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:


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 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:


Paste_image.png

PIL Making verification Code

Using all of these, and the random generator we learned before randomly can make a verification code,
generate a CAPTCHA code

#!/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 letter of the decimal ascii an = Random.randint (48, 57) # turns into a character according to the ASCII code, return back to the return Chr (AN) # disturbance def Rnd_dis (): "' With    Machine A disturbance 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 (32, 1 ) def Create_code (): # x 60:width = 4 * height = 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.d Raw (image) # fills each pixel: for x in range (0, width, max): for y in range (0, height, ten): Draw.point ((x, y), Fill=rnd_colo R ()) # fill character _str = "" # Fill in 4 random numbers or letters as CAPTCHA for T in range (4): c = Rnd_char () _str = "{} {}". Format (_str, c) # with        Machine distance picture top height, but at least distance of 30 pixels h = random.randint (1, height-30) # width, each character occupies picture width 1/4, plus 10 pixels gap w = width/4 * t + 10 Draw.text ((W, h), C, Font=font, Fill=rnd_color2 ()) # in the actual project, the verification code is saved in the database, plus the Time field print ("Save Captcha {} to database". Format (_STR)) #        Add character interference to the picture, intensity is controlled by 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 away h = random.randint (1, height-30) Draw.text ((W, h), Dis, Font=font, Fill=rndcolor ()) # Blur: Image.filter (image Filter.blur) # UUID1 generates a unique string as the captcha picture name Code_name = ' {}.jpg '. Format (UUID1 ()) Save_dir = './{} '. Format (Code_name) IM Age.save (Save_dir, ' jpeg') print ("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

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.
626062078, we 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.