import random
# 定義變量,用於畫面的背景色、寬、高
bgcolor = (random.randrange(20, 100), random.randrange(
20, 100), 255)
width = 100
height = 25
# 創建畫面對象
im = Image.new('RGB', (width, height), bgcolor)
# 創建畫筆對象
draw = ImageDraw.Draw(im)
# 調用畫筆的point()函數繪製噪點
for i in range(0, 100):
xy = (random.randrange(0, width), random.randrange(0, height))
fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
draw.point(xy, fill=fill)
# 定義驗證碼的備選值
str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
# 隨機選取4個值作爲驗證碼
rand_str = ''
for i in range(0, 4):
rand_str += str1[random.randrange(0, len(str1))]
# 構造字體對象,ubuntu的字體路徑爲“/usr/share/fonts/truetype/freefont”
font = ImageFont.load_default().font
# 構造字體顏色
fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
# 繪製4個字
draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
# 釋放畫筆
del draw
自動生成驗證碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.