python圖形圖像處理--驗證碼的製做

from PIL import Image,ImageDraw,ImageFontimport randomfrom io import BytesIOclass code():    def __init__(self):        self.codelen=4        self.codeCon="ABCDEFG23456789acbdsvjhn"        self.width=120        self.height=60        self.im=None        self.lineNum=0        self.pointNum=0    def randBgColor(self):        return  (random.randint(0,120),random.randint(0,120),random.randint(0,120),220)    def create(self):        self.bg=self.randBgColor()        self.im=Image.new("RGBA",size=(self.width,self.height),color=self.bg)    def randFgColor(self):        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255),255)    def lines(self):        lineNum=self.lineNum or random.randint(5,10)        draw = ImageDraw.Draw(self.im)        for itenm in range(lineNum):            place=(random.randint(0,self.width),random.randint(0,self.height),random.randint(0,self.width),random.randint(0,self.height))            draw.line(place,fill=self.randFgColor(),width=random.randint(1,2))    def point(self):        pointNum = self.pointNum or random.randint(20, 60)        draw = ImageDraw.Draw(self.im)        for itenm in range(pointNum):            place = (random.randint(0, self.width), random.randint(0, self.height))            draw.point(place, fill=self.randFgColor())    def rote(self):        self.im=self.im.rotate(random.randint(-10,20))        im1=Image.new("RGBA",size=(self.width,self.height),color=self.bg)        self.im=Image.composite(self.im,im1,self.im)    def text(self):        draw = ImageDraw.Draw(self.im)        for item in range(self.codelen):            self.codeCon[random.randint(0,len(self.codeCon)-1)]            text=self.codeCon[random.randint(0,len(self.codeCon)-1)]            draw.text((item*self.width/self.codelen,random.randint(0,self.height-40)),text,fill=self.randFgColor(),font=ImageFont.truetype("C:/Windows/Fonts/AdobeSongStd-Light.otf",random.randint(26,50)))        self.rote()    def output(self):        self.create()        self.lines()        self.point()        self.text()        self.im.show()        # self.im.save("11.png","png")        bt=BytesIO()        self.im.save(bt,"png")  #保存內存        return  bt.getvalue()codeobj=code()codeobj.output()
相關文章
相關標籤/搜索