python PIL模块与随机生成中文验证码


Posted in Python onFebruary 27, 2016

在这之前,你首先得了解Python中的PIL库。PIL是Python Imaging Library的简称,PIL是一个Python处理图片的库,提供了一系列模块和方法,比如:裁切,平移,旋转,改变尺寸等等。在PIL库中,任何一个图像都是用Image对象来表示的,所以要加载一张图片,最简单的形式如下:

from PIL import Image
image = Image.open("1.jpeg")

在PIL库中,最常用的模块有Image,ImageDraw,ImageEnhance,ImageFile等。
PIL的下载地址为:http://www.pythonware.com/products/pil/
接下来学习PIL中一些常见的操作:

(1)改变图片大小

from PIL import Image

image = Image.open("1.jpeg")
new_img = image.resize((256,256),Image.BILINEAR)
new_img.save("2.jpeg")

(2)旋转图片

from PIL import Image

image = Image.open("1.jpeg")
new_img = image.rotate(45)
new_img.save("2.jpeg")

(3)直线绘制

PIL库中的ImageDraw模块提供了图形绘制的基本功能,可以绘制直线,弧线,椭圆,矩形等等。

from PIL import Image,ImageDraw

image = Image.open("2.jpeg")
draw = ImageDraw.Draw(image)
width,height = image.size
draw.line(((0,0),(width-1,height-1)),fill=255)
draw.line(((0,height-1),(width-1,0)),fill=255)
image.save("2.jpeg")

(4)绘制圆

from PIL import Image,ImageDraw

image = Image.open("2.jpeg")
draw = ImageDraw.Draw(image)
width,height = image.size
draw.arc((0,0,width-1,height-1),0,360,fill=255)
image.save("2.jpeg")

更多方法可以参见帮助文档。

现在我们来研究利用Python如何生成中文验证码。其实这个问题简单,我们都知道验证码一般是用来防止网络机器

人采用无限次数的登录尝试破解密码,那么我们需要对这张图片随机生成中文字符来验证,一般来说会把图片的字表

现得很模糊,这样有效地防止机器人识别。所以我们除了要随机生成汉字,还要加入一些干扰线条等等。

# -*- coding: utf-8 -*-
from PIL import Image,ImageDraw,ImageFont
import random
import math, string 

class RandomChar():
 @staticmethod
 def Unicode():
  val = random.randint(0x4E00, 0x9FBF)
  return unichr(val) 

 @staticmethod
 def GB2312():
  head = random.randint(0xB0, 0xCF)
  body = random.randint(0xA, 0xF)
  tail = random.randint(0, 0xF)
  val = ( head << 8 ) | (body << 4) | tail
  str = "%x" % val
  return str.decode('hex').decode('gb2312') 

class ImageChar:
 def __init__(self, fontColor = (0, 0, 0),
           size = (100, 40),
           fontPath = 'SIMSUN.TTC',
           bgColor = (255, 255, 255),
           fontSize = 20):
  self.size = size
  self.fontPath = fontPath
  self.bgColor = bgColor
  self.fontSize = fontSize
  self.fontColor = fontColor
  self.font = ImageFont.truetype(self.fontPath, self.fontSize)
  self.image = Image.new('RGB', size, bgColor) 

 def rotate(self):
  self.image.rotate(random.randint(0, 30), expand=0) 

 def drawText(self, pos, txt, fill):
  draw = ImageDraw.Draw(self.image)
  draw.text(pos, txt, font=self.font, fill=fill)

 def randRGB(self):
  return (random.randint(0, 255),
      random.randint(0, 255),
      random.randint(0, 255)) 

 def randPoint(self):
  (width, height) = self.size
  return (random.randint(0, width), random.randint(0, height)) 

 def randLine(self, num):
  draw = ImageDraw.Draw(self.image)
  for i in range(0, num):
   draw.line([self.randPoint(), self.randPoint()], self.randRGB())

 def randChinese(self, num):
  gap = 5
  start = 0
  for i in range(0, num):
   char = RandomChar().GB2312()
   x = start + self.fontSize * i + random.randint(0, gap) + gap * i
   self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB())
   self.rotate()
  self.randLine(18) 

 def save(self, path):
  self.image.save(path)

ic = ImageChar(fontColor=(100,211, 90))
ic.randChinese(4)
ic.save("1.jpeg")

运行结果:

python PIL模块与随机生成中文验证码

Python 相关文章推荐
高性能web服务器框架Tornado简单实现restful接口及开发实例
Jul 16 Python
Python单元测试框架unittest使用方法讲解
Apr 13 Python
Python之str操作方法(详解)
Jun 19 Python
python 对dataframe下面的值进行大规模赋值方法
Jun 09 Python
python实现点对点聊天程序
Jul 28 Python
在python中安装basemap的教程
Sep 20 Python
python遍历文件夹找出文件夹后缀为py的文件方法
Oct 21 Python
详解Python字符串切片
May 20 Python
python numpy之np.random的随机数函数使用介绍
Oct 06 Python
Python笔记之代理模式
Nov 20 Python
python操作yaml说明
Apr 08 Python
selenium切换标签页解决get超时问题的完整代码
Aug 30 Python
Pythont特殊语法filter,map,reduce,apply使用方法
Feb 27 #Python
python 网络爬虫初级实现代码
Feb 27 #Python
Python数据库的连接实现方法与注意事项
Feb 27 #Python
学习python之编写简单简单连接数据库并执行查询操作
Feb 27 #Python
学习python之编写简单乘法口诀表实现代码
Feb 27 #Python
学习python 之编写简单乘法运算题
Feb 27 #Python
python学习之编写查询ip程序
Feb 27 #Python
You might like
新的一年,新的期待:DC在2020年的四部动画电影
2020/01/01 欧美动漫
PHP iconv 解决utf-8和gb2312编码转换问题
2010/04/12 PHP
php简单实现批量上传图片的方法
2016/05/09 PHP
Aliyun Linux 编译安装 php7.3 tengine2.3.2 mysql8.0 redis5的过程详解
2020/10/20 PHP
关于jquery.validate1.9.0前台验证的使用介绍
2013/04/26 Javascript
Javascript中实现String.startsWith和endsWith方法
2015/06/10 Javascript
基于JS实现的倒计时程序实例
2015/07/24 Javascript
jQuery 1.9.1源码分析系列(十五)之动画处理
2015/12/03 Javascript
node.js实现端口转发
2016/04/14 Javascript
获取IE浏览器Cookie信息的方法
2017/01/23 Javascript
原生JS实现动态加载js文件并在加载成功后执行回调函数的方法
2020/12/30 Javascript
JavaScript类型相关的常用操作总结
2019/02/14 Javascript
利用百度echarts实现图表功能简单入门示例【附源码下载】
2019/06/10 Javascript
node.JS二进制操作模块buffer对象使用方法详解
2020/02/06 Javascript
python根据文件大小打log日志
2014/10/09 Python
用python 制作图片转pdf工具
2015/01/30 Python
Python函数参数类型*、**的区别
2015/04/11 Python
python使用append合并两个数组的方法
2015/04/28 Python
Python3 SSH远程连接服务器的方法示例
2018/12/29 Python
Python OpenCV中的resize()函数的使用
2019/06/20 Python
python中for循环把字符串或者字典添加到列表的方法
2019/07/20 Python
Django继承自带user表并重写的例子
2019/11/18 Python
python如何变换环境
2020/07/21 Python
python批量修改文件名的示例
2020/09/27 Python
python 基于selectors库实现文件上传与下载
2020/12/31 Python
韩国女装NO.1网店:STYLENANDA
2016/09/16 全球购物
成人教育自我鉴定
2013/11/01 职场文书
机械制造与自动化应届生求职信
2013/11/16 职场文书
组织关系转移介绍信
2014/01/16 职场文书
致1500米运动员广播稿
2014/02/07 职场文书
村干部培训班主持词
2014/03/28 职场文书
体育教师求职信
2014/05/24 职场文书
思想工作总结范文
2015/08/12 职场文书
幼儿园中班教学反思
2016/03/03 职场文书
Python多个MP4合成视频的实现方法
2021/07/16 Python
公历12个月名称的由来
2022/04/12 杂记