本文主要是使用Python的第三方庫Pillow,使用其中的Image、ImageDraw、ImageFont、ImageFilter子產品實作了一個字母驗證碼圖檔的生成。
一、Pillow的安裝
pip install Pillow
注:pip工具需要自己安裝;
pillow的官網連結:https://pillow.readthedocs.io/en/5.2.x/
二、項目的代碼實作
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageFilter
import random
#生成驗證碼的字母
def rndChar():
return chr(random.randint(65,122))
#生成驗證碼的背景顔色
def rndColorBackGrond():
return (random.randint(128,255),random.randint(128,255),random.randint(128,255))
#生成驗證碼的字母顔色
def rndColorChar():
return(random.randint(0,128),random.randint(0,128),random.randint(0,128))
width = 240
height = 70
image = Image.new('RGB',(width,height),(0,0,0))
#建立Font對象
font=ImageFont.truetype('C:\Windows\Fonts\Arial.ttf',40)
#建立Draw對象
draw = ImageDraw.Draw(image)
#填充每個像素的顔色
for x in range(width):
for y in range(height):
draw.point((x,y),rndColorBackGrond())
for t in range(4):
draw.text((60*t+10,15),rndChar(),font=font,fill=rndColorChar())
image.save('VerificationCode.jpg','JPEG')
開發環境:Windows7
開發語言:Python
三、項目結果

注:由于作者水準有限,若有問題,請留言,謝謝!