Python module PIL module (generate random captcha image)

Source: Internet
Author: User

PiL profile what is PIL

PIL: is the abbreviation of the Python Image Library, the module of the graphics processing. The main classes include Image,imagefont,imagedraw,imagefilter

Import of PiL

First you need to install the pillow package

Pip Install Pillow

Then we can call the class in PiL.

From PIL import imagefrom PIL import imagefontfrom PIL import imagedrawfrom PIL import ImageFilter
PiL Common methods
Open ()  #打开图片new (mode,size,color)   #创建一张空白图片save ("Test.gif", "gif")   #保存 (new picture path and name, save format) size ()   # Gets the picture size thumbnail (weight,high)   #缩放图片大小 (wide, high) show ()    #显示图片blend (img1,img2,alpha)   #两张图片相加, Alpha represents the proportional parameters of img1 and Img2. Crop ()   #剪切, extracts an image of a matrix size. It receives a tuple of four elements as a parameter, each element being (left, upper, right, lower), and the origin of the coordinate system (0, 0) is the upper-top corner. Rotate    #逆时针旋转45度transpose ()    #旋转图像    Transpose (image.flip_left_right)       #左右对换.    Transpose (Image.flip_top_bottom)       #上下对换.    Transpose (image.rotate_90)             #旋转 90 degree angle.    Transpose (image.rotate_180)            #旋转 180 degree angle.    Transpose (image.rotate_270)            #旋转 270 degree angle. Paste (Im,box) #粘贴box大小的im到原先的图片对象中. Convert ()    #用来将图像转换为不同色彩模式. Filters ()     #滤镜    BLUR   #虚化    embossresize ((128,128))     #resize成128 *128 pixel size convert ("RGBA")    #图形类型转换getpixel (bis)) #获取某个像素位置的值putpixel ((bis)   , (255,0,0))    #写入某个像素位置的值
PIL applications

We mainly use the PIL to generate a random map of the verification code, below, we will step by step to do a small example

1. Create a fixed-size, fixed-color picture
From PIL import image# gets an Image object with the parameters RGB mode, respectively. Width 150, Height 30, red image = Image.new (' RGB ', (150,30), ' Red ') # saved to hard disk, named Test.png format for PNG picture Image.Save (Open (' Test.png ', ' WB '), ' PNG ')
2. Create a picture of a random color
From PIL import imageimport randomdef getrandomcolor (): "    get a random color (r,g,b) format '    c1 = Random.randint (0,255)    C2 = random.randint (0,255)    C3 = Random.randint (0,255)    return (C1,C2,C3) # Gets an image object with the parameters RGB mode, respectively. Width 150, Height 30, random color image = image.new (' RGB ', (150,30), Getrandomcolor ()) # Save to Hard disk, named Test.png format png picture Image.Save (' Test.png ', ' WB '), ' PNG ')
3. Create a picture of a random color with a fixed string
From PIL import imagefrom PIL import imagedrawfrom PIL import imagefontimport randomdef getrandomcolor (): '    get a random color (r,g,b) format "    c1 = Random.randint (0,255)    C2 = Random.randint (0,255)    C3 = Random.randint (0,255)    Return (C1,C2,C3) # Gets an image object with the parameters RGB mode, respectively. Width 150, Height 30, random color Image = image.new (' RGB ', (150,30), Getrandomcolor ()) # Get a Brush object, pass the picture object over Draw = Imagedraw.draw (image) # Get a font Font object parameter is the directory of the TTF fonts file, and the font size font=imagefont.truetype ("Kumo.ttf", size=32) # write something on the picture, the parameters are: positioning, string, color, Font Draw.text ((20,0), ' Fuyong ', Getrandomcolor (), Font=font) # saved to hard disk, named Test.png format png picture image.save (' test.png ', ' WB '), ' PNG ')

Effect:

4. Create a picture with random string random color
From PIL import imagefrom PIL import imagedrawfrom PIL import imagefontimport randomdef getrandomcolor (): ' Get a random color (r , g,b) format "C1 = Random.randint (0,255) c2 = Random.randint (0,255) C3 = Random.randint (0,255) return (C1,C2,C3) Def getrandomstr (): ' Gets a random string, and the color of each character is also random ' random_num = str (random.randint (0, 9)) Random_low_alpha = Chr (ra Ndom.randint (122)) Random_upper_alpha = Chr (random.randint (+)) Random_char = Random.choice ([Random_num, ran Dom_low_alpha, Random_upper_alpha]) return random_char# gets an image object with the parameters RGB mode, respectively. Width 150, Height 30, random color Image = image.new (' RGB ', (150,30), Getrandomcolor ()) # Get a Brush object, pass the picture object over Draw = Imagedraw.draw (image) # Gets a font font object parameter that is the directory of the fonts file for TTF, as well as the font size font=imagefont.truetype ("Kumo.ttf", size=26) for I in range (5): # loop 5 times, get 5 random string ran  Dom_char = Getrandomstr () # The random string that was written once on the picture, the parameters are: positioning, string, color, Font draw.text ((10+i*30, 0), Random_char, Getrandomcolor (), Font=font) # Save to Hard disk, named Test.png format png picture image.save (' test.png ', ' WB '), ' PNG ') 

Effect:

5. Generate a picture of the captcha with noise.
From PIL import imagefrom PIL import imagedrawfrom PIL import imagefontimport randomdef getrandomcolor (): ' Get a random color (r , g,b) format "C1 = Random.randint (0,255) c2 = Random.randint (0,255) C3 = Random.randint (0,255) return (C1,C2,C3) Def getrandomstr (): ' Gets a random string, and the color of each character is also random ' random_num = str (random.randint (0, 9)) Random_low_alpha = Chr (ra Ndom.randint (122)) Random_upper_alpha = Chr (random.randint (+)) Random_char = Random.choice ([Random_num, ran Dom_low_alpha, Random_upper_alpha]) return random_char# gets an image object with the parameters RGB mode, respectively. Width 150, Height 30, random color Image = image.new (' RGB ', (150,30), Getrandomcolor ()) # Get a Brush object, pass the picture object over Draw = Imagedraw.draw (image) # Gets a font font object parameter that is the directory of the fonts file for TTF, as well as the font size font=imagefont.truetype ("Kumo.ttf", size=26) for I in range (5): # loop 5 times, get 5 random string ran  Dom_char = Getrandomstr () # The random string that was written once on the picture, the parameters are: positioning, string, color, Font draw.text ((10+i*30, 0), Random_char, Getrandomcolor (), Font=font) # noise noise line width=150height=30# Dash for I in range (5): X1=random.ranDint (0,width) x2=random.randint (0,width) y1=random.randint (0,height) y2=random.randint (0,height) draw.line ((x1 , Y1,x2,y2), Fill=getrandomcolor ()) # Draw point for I in range: Draw.point ([Random.randint (0, width), random.randint (0, Heigh  T)], Fill=getrandomcolor ()) x = Random.randint (0, width) y = random.randint (0, height) draw.arc ((x, y, x + 4, y + 4), 0, Fill=getrandomcolor, ())
# Save to hard disk, named Test.png format PNG picture image.save (Open (' Test.png ', ' WB '), ' PNG ')

Effect:

6, the Verification code picture generation to encapsulate
From PIL import imagefrom PIL import imagedrawfrom PIL import imagefontimport randomclass validcodeimg:def __init__ (SE lf,width=150,height=30,code_count=5,font_size=32,point_count=20,line_count=3,img_format= ' png '): ' Can generate a The picture of the random verification code after noise reduction:p aram Width: Picture width unit px:p aram Height: Picture height unit px:p Aram Code_count: Number of verification codes:p Aram Font_size: Font size:p Aram Point_count: Number of noise points:p Aram Line_Count: Number of dashes:p Aram Img_format: Image format: Retu         RN generates a picture of the bytes type of data "Self.width = width self.height = Height Self.code_count = code_count Self.font_size = font_size Self.point_count = Point_count Self.line_count = Line_Count self.i Mg_format = Img_format @staticmethod def getrandomcolor (): "Gets a random color (r,g,b) format of ' C1 = Random.randin    T (0,255) C2 = Random.randint (0,255) C3 = Random.randint (0,255) return (C1,C2,C3) @staticmethod     Def getrandomstr ():   "' Gets a random string, and the color of each character is also random ' random_num = str (random.randint (0, 9)) Random_low_alpha = Chr (random.randint        (97, 122)) Random_upper_alpha = Chr (random.randint (+)) Random_char = Random.choice ([Random_num, Random_low_alpha, random_ Upper_alpha] Return Random_char def getvalidcodeimg (self): # Gets an Image object, the parameters are RGB mode, respectively.        Width 150, Height 30, random color image = image.new (' RGB ', (self.width,self.height), Self.getrandomcolor ()) # Get a Brush object, pass the picture object over Draw = Imagedraw.draw (image) # Gets a font font object parameter is the TTF font file's directory, as well as the font size font=imagefont.truetype ("Kumo.ttf", si ze=self.font_size) temp = [] for I in range (Self.code_count): # loop 5 times, get 5 random strings Random_  char = Self.getrandomstr () # The random string that was written once on the picture, the parameters are: positioning, string, color, Font draw.text ((10+i*30,-2), Random_char, Self.getrandomcolor (), Font=font) # saves random characters for verifying that the user entered the correct code when using Temp.append (Random_char) Vali     D_str = "". Join (temp)   # Noise Noise Line # Dash for I in range (Self.line_count): X1=random.randint (0,self.width) X2=ran            Dom.randint (0,self.width) y1=random.randint (0,self.height) y2=random.randint (0,self.height) Draw.line ((X1,y1,x2,y2), Fill=self.getrandomcolor ()) # Draw Dot for I in range (self.point_count): DRA W.point ([Random.randint (0, Self.width), Random.randint (0, Self.height)], Fill=self.getrandomcolor ()) x = random . Randint (0, self.width) y = random.randint (0, Self.height) Draw.arc ((x, y, x + 4, y + 4), 0,, fil L=self.getrandomcolor ()) # Generate pictures in memory from IO import Bytesio f = Bytesio () image.save (F, self.img _format) data = F.getvalue () f.close () return data,valid_strif __name__ = ' __main__ ': img = valid CODEIMG () data, valid_str = Img.getvalidcodeimg () print (VALID_STR) f = open (' Test.png ', ' WB ') f.write (data)

  

Effect:

7, applied to the actual development

Login.html

<input id= "Valid-inp" name= "Validcode" class= "Form-control" type= "password" placeholder= "Please enter the verification code" autocomplete= " Off ">             <span id=" valid-img "></ Span>

urls.py

From django.conf.urls import urlfrom django.contrib import adminfrom Blog Import viewsurlpatterns = [    url (r ' ^admin/'), admin.site.urls),    url (r ' ^$ ', views. Main.as_view (), name= ' main '),    url (r ' ^login$ ', views. Login.as_view (), name= ' login '),    # login page Verification code picture Request    URL (r ' ^get_valid_img ', views. Getvalidimg.as_view (), name= ' get_valid_img '),]

views.py

Class Main (view): Def get (self,request): Return render (Request, ' main.html ') class Login (view): Def get (self,re Quest): Return render (Request, ' login.html ') def post (self,request): username = Request. Post.get (' username ') password = Request. Post.get (' password ') Valid_code = Request. Post.get (' Valid_code ') # print (valid_code) # Print (Request.session.get (' Valid_code ')) if valid_code.u        Pper ()! = Request.session.get (' Valid_code '). Upper (): Return Jsonresponse ({' state ': False, ' msg ': ' Authenticode error '}) user = Auth.authenticate (request,username=username,password=password) If User: # login is successful, write to users via Auth login method To the session auth.login (Request,user) # submit Form login Successful after jump to the user's own blog home redirect_url = '/{} '. Format (US Er.username) return Jsonresponse ({' state ': True, ' msg ': ' Login successful! ', ' url ': redirect_url}) Else:return Jsonresponse ({' state ': false, ' msg ': ' Username or password error! '}) class Getvalidimg (View): Def get (self,request): obj = validcodeimg () Img_data,valid_code = Obj.getvalidcodeimg () req uest.session[' valid_code ' = Valid_code return HttpResponse (img_data)

  

Python module PIL module (generate random captcha image)

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.