python產生驗證碼

來源:互聯網
上載者:User

標籤:imp   int   ima   save   image   div   rgb   pil   寬度   

#encoding=utf-8import random# import matplotlib.pyplot as pltimport stringimport sysimport mathfrom PIL import Image,ImageDraw,ImageFont,ImageFilterfilename="C:/Users/123/Desktop/yzm/"#字型的位置,不同版本的系統會有不同BuxtonSketch.ttffont_path = ‘C:/Windows/Fonts/Georgia.ttf‘#font_path = ‘C:/Windows/Fonts/默陌肥圓手寫體.ttf‘#產生幾位元的驗證碼number = 4#產生驗證碼圖片的高度和寬度size = (129,53)#背景顏色,預設為白色bgcolor = (255,255,255)#字型顏色,預設為藍色fontcolor = (0,0,0)#幹擾線顏色。預設為紅色linecolor = (0,0,0)#是否要加入幹擾線draw_line = True#加入幹擾線條數的上下限line_number = (1,5)#用來隨機產生一個字串def gene_text():    # source = list(string.letters)    # for index in range(0,10):    #     source.append(str(index))    source = [‘0‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘]    # source = [ ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘,‘I‘,‘J‘, ‘K‘,‘L‘, ‘M‘, ‘N‘,‘O‘,‘P‘,‘Q‘,‘R‘,    #           ‘S‘, ‘T‘, ‘U‘, ‘V‘, ‘W‘, ‘Z‘,‘X‘, ‘Y‘]    return ‘‘.join(random.sample(source,number))#number是產生驗證碼的位元#用來繪製幹擾線def gene_line(draw,width,height):    # begin = (random.randint(0, width), random.randint(0, height))    # end = (random.randint(0, width), random.randint(0, height))    begin = (0, random.randint(0, height))    end = (74, random.randint(0, height))    draw.line([begin, end], fill = linecolor,width=3)#產生驗證碼def gene_code():    width,height = size #寬和高    image = Image.new(‘RGBA‘,(width,height),bgcolor) #建立圖片    font = ImageFont.truetype(font_path,40) #驗證碼的字型    draw = ImageDraw.Draw(image)  #建立畫筆    text = gene_text() #產生字串    font_width, font_height = font.getsize(text)    draw.text(((width - font_width) / number, (height - font_height) / number),text,            font= font,fill=fontcolor) #填充字串    if draw_line:        gene_line(draw,width,height)    image = image.transform((width+30,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)  #建立扭曲    # image = image.transform((width+20,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)  #建立扭曲    image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #濾鏡,邊界加強    # a = str(m)    aa = str(".png")    path = filename + text + aa    # cv2.imwrite(path, I1)    # image.save(‘idencode.jpg‘) #儲存驗證碼圖片    image.save(path)x=1# if __name__ == "__main__":# for k in(1,1000):while x<20:     gene_code()     x+=1

  

python產生驗證碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.