python寫個驗證碼


用python寫一個驗證碼功能

分析:

1、驗證碼背景

2、驗證碼包含26個字母大小寫以及0-9十個數字

擴展需求:3、添加濾鏡模糊等

 

這里使用python中專門處理圖片的PIL庫

from PIL import ImageFont,ImageDraw,Image
import random
from io import BytesIO
def get_random():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)RGB模式下的顏色信息 def get_code(request):
    img_obj=Image.new('RGB',(200,50),get_random()) 創建圖片
    img_draw=ImageDraw.Draw(img_obj)  生成畫筆
    img_font=ImageFont.truetype('static/font/333.ttf',50) 字體和文字大小

    upper_str=chr(random.randint(65,90))    利用ASCII碼來生成大寫小寫的的文字
    lower_str=chr(random.randint(97,122))
    num_str=str(random.randint(0,9))
    code=''
    for i in range(5):  每次隨機拿出一個字母或者數字
        res=random.choice([upper_str,lower_str,num_str])
        img_draw.text((10+i*40,5),res,get_random(),img_font)
        code+=res
    io_obj=BytesIO()  生成二進制文件對象
    img_obj.save(io_obj,'png') 將生成的驗證碼圖片存入文件對象中
    request.session['code']=code
    print(code)
    return HttpResponse(io_obj.getvalue()) 

IO模塊 即input、output 指的是文件的寫入和讀取

IO中的BytesIO方法是從內存中讀寫,咱們把生成的文件存入BytesIO對象中,需要的時候再用getvalue()的方法取出來

與之類似的還有StringIO,StringIO操作的只能是str,如果要操作二進制數據,就需要使用BytesIO。

 

另附一個大佬寫的驗證碼

#coding=utf-8
import random
import string
import sys
import math
from PIL import Image,ImageDraw,ImageFont,ImageFilter
 
#字體的位置,不同版本的系統會有不同
font_path = '/Library/Fonts/Arial.ttf'
#生成幾位數的驗證碼
number = 4
#生成驗證碼圖片的高度和寬度
size = (100,30)
#背景顏色,默認為白色
bgcolor = (255,255,255)
#字體顏色,默認為藍色
fontcolor = (0,0,255)
#干擾線顏色。默認為紅色
linecolor = (255,0,0)
#是否要加入干擾線
draw_line = True
#加入干擾線條數的上下限
line_number = (1,5)
 
#用來隨機生成一個字符串
def gene_text():
    source = list(string.letters)
    for index in range(0,10):
        source.append(str(index))
    return ''.join(random.sample(source,number))#number是生成驗證碼的位數
#用來繪制干擾線
def gene_line(draw,width,height):
    begin = (random.randint(0, width), random.randint(0, height))
    end = (random.randint(0, width), random.randint(0, height))
    draw.line([begin, end], fill = linecolor)
 
#生成驗證碼
def gene_code():
    width,height = size #寬和高
    image = Image.new('RGBA',(width,height),bgcolor) #創建圖片
    font = ImageFont.truetype(font_path,25) #驗證碼的字體
    draw = ImageDraw.Draw(image)  #創建畫筆
    text = gene_text() #生成字符串
    font_width, font_height = font.getsize(text)
    draw.text(((width - font_width) / number, (height - font_height) / number),text,
            font= font,fill=fontcolor) #填充字符串
    if draw_line:
        gene_line(draw,width,height)
    # image = image.transform((width+30,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)  #創建扭曲
    image = image.transform((width+20,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)  #創建扭曲
    image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #濾鏡,邊界加強
    image.save('idencode.png') #保存驗證碼圖片
if __name__ == "__main__":
    gene_code()

轉自https://www.cnblogs.com/yangdianfeng007/p/5438193.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM