萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> python使用pil生成圖片驗證碼的方法

python使用pil生成圖片驗證碼的方法

   這篇文章主要介紹了python使用pil生成圖片驗證碼的方法,涉及Python操作Image,ImageDraw,ImageFont等模塊的相關技巧,需要的朋友可以參考下

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 # -*- coding: utf-8 -*- #導入三個模塊 import Image,ImageDraw,ImageFont import random import math '''基本功能''' #圖片寬度 width = 100 #圖片高度 height = 40 #背景顏色 bgcolor = (255,255,255) #生成背景圖片 image = Image.new('RGB',(width,height),bgcolor) #加載字體 font = ImageFont.truetype('FreeSans.ttf',30) #字體顏色 fontcolor = (0,0,0) #產生draw對象,draw是一些算法的集合 draw = ImageDraw.Draw(image) #畫字體,(0,0)是起始位置 draw.text((0,0),'1234',font=font,fill=fontcolor) #釋放draw del draw #保存原始版本 image.save('1234_1.jpeg') '''演示扭曲,需要新建一個圖片對象''' #新圖片 newImage = Image.new('RGB',(width,height),bgcolor) #load像素 newPix = newImage.load() pix = image.load() offset = 0 for y in range(0,height): offset += 1 for x in range(0,width): #新的x坐標點 newx = x + offset #你可以試試如下的效果 #newx = x + math.sin(float(y)/10)*10 if newx < width: #把源像素通過偏移到新的像素點 newPix[newx,y] = pix[x,y] #保存扭曲後的版本 newImage.save('1234_2.jpeg') '''形變一下''' #x1 = ax+by+c #y1 = dx+ey+f newImage = image.transform((width+30,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0)) newImage.save('1234_3.jpeg') '''畫干擾線,別畫太多,免得用戶都看不清楚''' #創建draw,畫線用 draw = ImageDraw.Draw(newImage) #線的顏色 linecolor= (0,0,0) for i in range(0,15): #都是隨機的 x1 = random.randint(0,width) x2 = random.randint(0,width) y1 = random.randint(0,height) y2 = random.randint(0,height) draw.line([(x1, y1), (x2, y2)], linecolor) #保存到本地 newImage.save('1234_4.jpeg')

  希望本文所述對大家的Python程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved