Python 生成一個驗證碼

生成一個驗證碼最主要的就是引用PIL(Python Imaging Library);PIL是Python平臺事實上的圖像處理標準庫了。

生成驗證碼需要的一個數據的顏色,隨機的數字或者字母

一.隨機顏色

import random
def getRandomColor():
        '''獲取一個隨機顏色(r,g,b)格式的'''
        c1 = random.randint(0,255)
        c2 = random.randint(0,255)
        c3 = random.randint(0,255)
        #print '=====',(c1,c2,c3)
        return (c1,c2,c3)

二.隨機數字和字母

import random
def getRandomStr():
        '''獲取一個隨機字符串,每個字符的顏色也是隨機的'''
        random_num = str(random.randint(0, 9))
        random_low_alpha = chr(random.randint(97, 122))
        random_upper_alpha = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
        print '---->',random_char
        return random_char

三.設置圖片的規格數據等

def __init__(self,width=150,height=30,code_count=5,font_size=24,point_count=20,line_count=3,img_format='png'):
        '''
        可以生成一個經過降噪後的隨機驗證碼的圖片
        :param width: 圖片寬度 單位px
        :param height: 圖片高度 單位px
        :param code_count: 驗證碼個數
        :param font_size: 字體大小
        :param point_count: 噪點個數
        :param line_count: 劃線個數
        :param img_format: 圖片格式
        '''
        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.img_format = img_format

四。得到驗證碼圖片

 def getValidCodeImg(self):
        # 獲取一個Image對象,參數分別是RGB模式。寬150,高30,隨機顏色
        #print 'ssssss',self.width
        image = Image.new('RGB',(self.width,self.height),getRandomColor())
 
        # 獲取一個畫筆對象,將圖片對象傳過去
        draw = ImageDraw.Draw(image)
 
        # 獲取一個font字體對象參數是ttf的字體文件的目錄,以及字體的大小
        font=ImageFont.truetype("/home/dawn/ssvn/PIL/font1/simsun.ttf",size=self.font_size)
 
        temp = []
        for i in range(self.code_count):
            # 循環5次,獲取5個隨機字符串
            random_char = getRandomStr()
 
            # 在圖片上一次寫入得到的隨機字符串,參數是:定位,字符串,顏色,字體
            draw.text((10+i*30,-2),random_char , getRandomColor(),font = font)
 
            # 保存隨機字符,以供驗證用戶輸入的驗證碼是否正確時使用
            temp.append(random_char)
        valid_str = "".join(temp)
 
        # 噪點噪線
        # 劃線
        for i in range(self.line_count):
            x1=random.randint(0,self.width)
            x2=random.randint(0,self.width)
            y1=random.randint(0,self.height)
            y2=random.randint(0,self.height)
            draw.line((x1,y1,x2,y2),fill=getRandomColor())
 
        # 畫點
        for i in range(self.point_count):
            draw.point([random.randint(0, self.width), random.randint(0, self.height)], fill=getRandomColor())
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            draw.arc((x, y, x + 4, y + 4), 0, 90, fill=getRandomColor())
 
        # 在內存生成圖片
        from io import BytesIO
        f = BytesIO()
        image.save(f, self.img_format)
        data = f.getvalue()
        f.close()
 
        return data,valid_str

最終代碼:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import random

def getRandomColor():
        '''獲取一個隨機顏色(r,g,b)格式的'''
        c1 = random.randint(0,255)
        c2 = random.randint(0,255)
        c3 = random.randint(0,255)
        #print '=====',(c1,c2,c3)
        return (c1,c2,c3)

def getRandomStr():
        '''獲取一個隨機字符串,每個字符的顏色也是隨機的'''
        random_num = str(random.randint(0, 9))
        random_low_alpha = chr(random.randint(97, 122))
        random_upper_alpha = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
        print '---->',random_char
        return random_char

class ValidCodeImg:
    def __init__(self,width=150,height=30,code_count=5,font_size=24,point_count=20,line_count=3,img_format='png'):
        '''
        可以生成一個經過降噪後的隨機驗證碼的圖片
        :param width: 圖片寬度 單位px
        :param height: 圖片高度 單位px
        :param code_count: 驗證碼個數
        :param font_size: 字體大小
        :param point_count: 噪點個數
        :param line_count: 劃線個數
        :param img_format: 圖片格式
        '''
        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.img_format = img_format


     

    def getValidCodeImg(self):
        # 獲取一個Image對象,參數分別是RGB模式。寬150,高30,隨機顏色
        #print 'ssssss',self.width
        image = Image.new('RGB',(self.width,self.height),getRandomColor())
 
        # 獲取一個畫筆對象,將圖片對象傳過去
        draw = ImageDraw.Draw(image)
 
        # 獲取一個font字體對象參數是ttf的字體文件的目錄,以及字體的大小
        font=ImageFont.truetype("/home/dawn/ssvn/PIL/font1/simsun.ttf",size=self.font_size)
 
        temp = []
        for i in range(self.code_count):
            # 循環5次,獲取5個隨機字符串
            random_char = getRandomStr()
 
            # 在圖片上一次寫入得到的隨機字符串,參數是:定位,字符串,顏色,字體
            draw.text((10+i*30,-2),random_char , getRandomColor(),font = font)
 
            # 保存隨機字符,以供驗證用戶輸入的驗證碼是否正確時使用
            temp.append(random_char)
        valid_str = "".join(temp)
 
        # 噪點噪線
        # 劃線
        for i in range(self.line_count):
            x1=random.randint(0,self.width)
            x2=random.randint(0,self.width)
            y1=random.randint(0,self.height)
            y2=random.randint(0,self.height)
            draw.line((x1,y1,x2,y2),fill=getRandomColor())
 
        # 畫點
        for i in range(self.point_count):
            draw.point([random.randint(0, self.width), random.randint(0, self.height)], fill=getRandomColor())
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            draw.arc((x, y, x + 4, y + 4), 0, 90, fill=getRandomColor())
 
        # 在內存生成圖片
        from io import BytesIO
        f = BytesIO()
        image.save(f, self.img_format)
        data = f.getvalue()
        f.close()
 
        return data,valid_str




if __name__ == '__main__':
 
    img = ValidCodeImg()
    data, valid_str = img.getValidCodeImg()
    print(valid_str)
 
    f = open('test.png', 'wb')
    f.write(data)

注意:font=ImageFont.truetype("/home/dawn/ssvn/PIL/font1/simsun.ttf",size=self.font_size) 中文字需要自己文件字體

需要的可以去下載https://download.csdn.net/download/dawn_02/11960817

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章