pillow模塊PIL:Python Imaging Library,已經(jīng)是Python平臺事實(shí)上的圖像處理標(biāo)準(zhǔn)庫了。PIL功能非常強(qiáng)大,但API卻非常簡單易用。 由于PIL僅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基礎(chǔ)上創(chuàng)建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了許多新特性,因此,我們可以直接安裝使用Pillow。 安裝pillowpycharm安裝命令行安裝Python中引入from PIL import Image #生成一張圖片的第三方模塊 from PIL import ImageDraw #在圖片上寫字 from PIL import ImageFont #生成字體對象 PIL使用之驗(yàn)證碼ps:驗(yàn)證碼臨時(shí)存入內(nèi)存 from io import BytesIO #內(nèi)存管理器(存臨時(shí)驗(yàn)證碼) 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) # 把驗(yàn)證碼存到session request.session['valid_code']=valid_code # 打開一個內(nèi)存管理器,保存進(jìn)去 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 前端點(diǎn)擊更換驗(yàn)證碼<img src="/get_code/" class="col-xs-8" style="padding-left: 5px;padding-right: 1px" alt="" height="34" id="id_img"> <script> //點(diǎn)擊圖片刷新功能 $("#id_img").click(function () { $(this)[0].src=$(this)[0].src "?" }); </script> 生成隨機(jī)數(shù)顏色 ![]() def get_random_color(): ''' 生成3個隨機(jī)數(shù)顏色 ''' return (random.randint(0,255),random.randint(0,255),random.randint(0,255))get_random_color() ? 來源:http://www./content-4-186401.html |
|