码迷,mamicode.com
首页 > 编程语言 > 详细

Python生成验证码

时间:2016-02-22 12:03:53      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

  1. 获取随机字符串

  2. 引入PIL包,生成画布、
  3. 创建字体,需要使用imagefont.truetype
  4. 获取随机背景颜色和字体颜色
  5. 将文字写入图像中去
  6. 保存图片

代码如下:

import random

import Image,ImageFilter

import ImageFont

import ImageDraw

#获取随机字符串

def getchar(len=6):

  #新建元组存储获得的字符串

  codelist=[]

  for i in range(10):#获取数字

    codelist.append(str(i))

  for i in range(65,91):#获取A-Z的字母

    codelist.append(str(i))

  for i in range(97,123):#获取a-z的字母

    codelist.append(str(i))

  code=random.sample(codeList,len)    #截取len个字符,返回的是一个元组

  verification=‘‘.join(code)      #将元组合并成字符串

  return verification

#创建画布

im=Image.new(‘RGB‘, (240,60), (255,255,255))

#创建字体,使用imagefont.truetype

font=ImageFont.truetype(‘C:\Windows\Fonts\Arial.ttf‘,42)#字体文件需要有才行

#获取随机背景颜色和字体颜色

#背景颜色

def getcolor():

  return (random.randint(65,255),random.randint(65,255),random.randint(65,255))

#字体颜色

def fontcolor():

  return (random.randint(35,127),random.randint(35,127),random.randint(35,127))

#将文字写到图像中去

draw=ImageDraw.Draw(im)

for x in range(240):

  for y in range(60):

    draw.point((x,y), fill=getcolor())

  for t in range(4):

    draw.text((60 * t + 10, 10), getchar(1),font=font,fill=fontcolor())

#保存验证码图像

  im.save(‘D:/test.png‘)

注意:运行的时候会报错,错误代码为ImportError: The _imagingft C module is not installed错误,只需要卸载PIL,重新安装编译过了的PIL版本即可

卸载PIL:pip uninstall PIL

需要使用到的包:import random

import Image,ImageFilter

import ImageFont

import ImageDraw

 

Python生成验证码

标签:

原文地址:http://www.cnblogs.com/biller/p/5206476.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!