python生成検証コード


コード:
#coding:utf-8
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import string,random

def getRandomChar():
    return [random.choice(string.letters)for _ in range(4)]

def getRandomColor():
    return (random.randint(30,100),random.randint(30,100),random.randint(30,100))

def getCodePicture():
    width=240
    height=60
    #    
    image=Image.new('RGB',(width,height),(180,180,180))
    font=ImageFont.truetype('./1.ttf',40)
    draw=ImageDraw.Draw(image)
    #       
    code=getRandomChar()
    #         
    for t in range(4):
        draw.text((60*t+10,0),code[t],font=font,fill=getRandomColor())
    #    
    for _ in range(random.randint(1500,3000)):
        draw.point((random.randint(0,width),random.randint(0,height)),fill=getRandomColor())
    #    
    image=image.filter(ImageFilter.BLUR)
    #           
    image.save("".join(code)+'.jpg','jpeg');
if __name__=='__main__':
    getCodePicture()

1、randomモジュール
  • random.choice   random.choiceはシーケンスからランダム要素を取得します.その関数のプロトタイプは:random.choice(sequence).パラメータsequenceは秩序タイプを表します.ここで、sequenceはpythonでは特定のタイプではなく、一連のタイプを指します.list,tuple,文字列はすべてsequenceに属する.次にchoiceを使用する例を示します.print random.义齿choice([“JGood”,”is”, “a”, “handsome”, “boy”]) print random.choice((“Tuple”,”List”, “Dict”))
  • random.randint   random.randint()の関数のプロトタイプは:random.randint(a,b)は、指定された範囲内の整数を生成するために使用される.ここで、パラメータaは下限、パラメータbは上限、生成乱数n:a<=n<=b、以下liz print random.randint(12,20)#生成乱数n:12<=n<=20 print random.randint(20,20)#結果は永遠に20
  • 2、ImageDrawオブジェクトdrawのdraw.text(),draw.ポイント()メソッド3、image.filter(ImageFilter.BLUR)ぼかし処理