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 相关文章推荐
在Python的Flask框架中实现单元测试的教程
Apr 20 Python
Python实现将目录中TXT合并成一个大TXT文件的方法
Jul 15 Python
Python中的os.path路径模块中的操作方法总结
Jul 07 Python
Python简单计算给定某一年的某一天是星期几示例
Jun 27 Python
python3实现二叉树的遍历与递归算法解析(小结)
Jul 03 Python
centos+nginx+uwsgi+Django实现IP+port访问服务器
Nov 15 Python
python利用JMeter测试Tornado的多线程
Jan 12 Python
Python list运算操作代码实例解析
Jan 20 Python
Tensorflow tf.nn.atrous_conv2d如何实现空洞卷积的
Apr 20 Python
Python with语句用法原理详解
Jul 03 Python
MATLAB 如何求取离散点的曲率最大值
Apr 16 Python
Python中requests库的用法详解
Jun 05 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
支持oicq头像的留言簿(一)
2006/10/09 PHP
ThinkPHP应用模式扩展详解
2014/07/16 PHP
php实现上传图片文件代码
2015/07/19 PHP
在WordPress中安装使用视频播放器插件Hana Flv Player
2016/01/04 PHP
php array_walk_recursive 使用自定的函数处理数组中的每一个元素
2016/11/16 PHP
PHP实现针对日期,月数,天数,周数,小时,分,秒等的加减运算示例【基于strtotime】
2017/04/19 PHP
关于Laravel参数验证的一些疑与惑
2019/11/19 PHP
jquery 新建的元素事件绑定问题解决方案
2014/06/12 Javascript
JS中的作用域链
2017/03/01 Javascript
javascript  数组排序与对象排序的实例
2017/07/17 Javascript
详解puppeteer使用代理
2018/12/27 Javascript
JavaScript常见鼠标事件与用法分析
2019/01/03 Javascript
vue单文件组件lint error自动fix与styleLint报错自动fix详解
2019/01/08 Javascript
js实现ATM机存取款功能
2020/10/27 Javascript
从零撸一个pc端vue的ui组件库( 计数器组件 )
2019/08/08 Javascript
利用JS代码自动删除稿件的普通弹幕功能
2019/09/20 Javascript
JavaScript的变量声明与声明提前用法实例分析
2019/11/26 Javascript
[02:28]DOTA2 2015国际邀请赛中国区预选赛首日现场百态
2015/05/26 DOTA
Python新手实现2048小游戏
2015/03/31 Python
python中format()函数的简单使用教程
2018/03/14 Python
Python 实现删除某路径下文件及文件夹的实例讲解
2018/04/24 Python
分享一下Python数据分析常用的8款工具
2018/04/29 Python
Python设计模式之命令模式原理与用法实例分析
2019/01/11 Python
Python3转换html到pdf的不同解决方案
2019/03/11 Python
Windows系统下pycharm中的pip换源
2020/02/23 Python
keras用auc做metrics以及早停实例
2020/07/02 Python
整理HTML5的一些新特性与Canvas的常用属性
2016/01/29 HTML / CSS
DNA基因检测和分析:23andMe
2019/05/01 全球购物
Linux常见面试题
2013/03/18 面试题
学生偷窃检讨书
2014/09/25 职场文书
2014年单位法制宣传日活动总结
2014/11/01 职场文书
2014年公路养护工作总结
2014/12/04 职场文书
教师工作能力自我评价
2015/03/04 职场文书
关于保护环境的建议书
2019/06/24 职场文书
html5调用摄像头截图功能
2022/01/18 Javascript
nginx location 带斜杠【 / 】与不带的区别
2022/04/13 Servers