1. 程式人生 > >用python做驗證碼

用python做驗證碼

引用PIL模組

效果圖展示:

from PIL import ImageDraw,ImageFont
from PIL import Image
import random
from io import BytesIO#在記憶體中建立
def get_random_color():
    color=(random.randint(0,255),random.randint(0,255),random.randint(0,255))
    return color
image=Image.new('RGB',(200,30),(255,255,255))
draw=ImageDraw.Draw(image)
for i in range(4):
    random_number=str(random.randint(0,9))
    random_lower_alpha=chr(random.randint(97,122))
    random_upper_alpha=chr(random.randint(65,90))
    rand_python=random.choice([random_number,random_lower_alpha,random_upper_alpha])
    draw.text((i*50+10,0),rand_python,get_random_color(),font=ImageFont.truetype('1.ttf',28),align='center')

for i in range(4):#製造線
    x1=random.randint(0,200)
    y1=random.randint(0,30)
    x2=random.randint(0,200)
    y2=random.randint(0,30)
    draw.line([(x1,y1),(x2,y2)],fill=get_random_color())

for i in range(100):#製造點
    x1=random.randint(0,200)
    y1=random.randint(0,30)
    x2=random.randint(0,200)
    y2=random.randint(0,30)
    draw.point([(x1,y1),(x2,y2)],fill=get_random_color())

f=open('驗證碼.jpg','wb')
image.save(f)
f.close()
#以下是在記憶體中建立驗證碼,比在磁碟上建立速度快
# f=BytesIO()
# image.save(f,'jpg')
# data=f.getvalue()
# f.close()