PIL:Python Imaging Library,已經(jīng)是Python平臺事實上的圖像處理標準庫了。PIL功能非常強大,但API卻非常簡單易用。
由于PIL僅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基礎上創(chuàng)建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了許多新特性,因此,我們可以直接安裝使用Pillow。
from PIL import Image #生成一張圖片的第三方模塊from PIL import ImageDraw #在圖片上寫字from PIL import ImageFont #生成字體對象
ps:驗證碼臨時存入內(nèi)存
from io import BytesIO #內(nèi)存管理器(存臨時驗證碼)
def get_code(request): # 生成一張新圖片 new_img = Image.new('RGB',(171,34),color=get_random_color()) # 把圖片放到ImageDraw.Draw內(nèi)(畫筆) draw = ImageDraw.Draw(new_img) # 構(gòu)造字體對象第一個參數(shù)是字體文件(ttf格式http://www.downcc.com/k/ttfziti/),第二個參數(shù)是字體大小 font = ImageFont.truetype('static/font/simsun.ttf',30) valid_code = '' for i in range(5): num_str = str(random.randint(0,9)) upper_str = chr(random.randint(65,90)) low_str = chr(random.randint(97,122)) random_str = random.choice([num_str,upper_str,low_str]) draw.text((i*28 20,1),random_str,get_random_color(),font=font) valid_code =random_str print(valid_code) # 把驗證碼存到session request.session['valid_code']=valid_code # 打開一個內(nèi)存管理器,保存進去 img = BytesIO() new_img.save(img,'png') # 從內(nèi)存管理器取出img data = img.getvalue() return HttpResponse(data)
code = request.POST.get('code')if code.upper() == request.session.get('valid_code').upper(): pass
<img src="/get_code/" class="col-xs-8" style="padding-left: 5px;padding-right: 1px" alt="" height="34" id="id_img"><script>//點擊圖片刷新功能 $("#id_img").click(function () { $(this)[0].src=$(this)[0].src "?" });</script>
生成隨機數(shù)顏色
def get_random_color(): ''' 生成3個隨機數(shù)顏色 ''' return (random.randint(0,255),random.randint(0,255),random.randint(0,255))get_random_color()
?
來源:http://www.icode9.com/content-4-186401.html