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和GO语言实现的消息摘要算法示例
Mar 10 Python
python创建临时文件夹的方法
Jul 06 Python
浅析python中SQLAlchemy排序的一个坑
Feb 24 Python
Python图像处理实现两幅图像合成一幅图像的方法【测试可用】
Jan 04 Python
Python实现将字符串的首字母变为大写,其余都变为小写的方法
Jun 11 Python
python飞机大战 pygame游戏创建快速入门详解
Dec 17 Python
tensorboard显示空白的解决
Feb 15 Python
Python爬虫防封ip的一些技巧
Aug 06 Python
Django修改app名称和数据表迁移方案实现
Sep 17 Python
PyQt5 QThread倒计时功能的实现代码
Apr 02 Python
Python中Cookies导出某站用户数据的方法
May 17 Python
Django drf请求模块源码解析
Jun 08 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
PHP安全编程之加密功能
2006/10/09 PHP
支持php4、php5的mysql数据库操作类
2008/01/10 PHP
php中用于检测一个地理IP地址是否可用的代码
2012/02/19 PHP
浅析get与post的一些特殊情况
2014/07/28 PHP
php类自动加载器实现方法
2015/07/28 PHP
php抓取并保存网站图片的实现代码
2015/10/28 PHP
php自定义分页类完整实例
2015/12/25 PHP
PHP 将dataurl转成图片image方法总结
2016/10/14 PHP
thinkphp5.0自定义验证规则使用方法
2017/11/16 PHP
jquery 插件 人性化的消息显示
2008/01/21 Javascript
javascript中setTimeout的问题解决方法
2014/05/08 Javascript
jquery实现搜索框常见效果的方法
2015/01/22 Javascript
深入学习JavaScript中的原型prototype
2015/08/13 Javascript
JavaScript的代码编写格式规范指南
2015/12/07 Javascript
浏览器兼容性问题大汇总
2015/12/17 Javascript
js定义类的几种方法(推荐)
2016/06/08 Javascript
jQuery中text() val()和html()的区别实例详解
2016/06/28 Javascript
JavaScript中创建对象的7种模式详解
2017/02/21 Javascript
AngularJS中filter的使用实例详解
2017/08/25 Javascript
用vue构建多页面应用的示例代码
2017/09/20 Javascript
JS实现匀速与减速缓慢运动的动画效果封装示例
2018/08/27 Javascript
javascript sort()对数组中的元素进行排序详解
2019/10/13 Javascript
深入讲解Python中面向对象编程的相关知识
2015/05/25 Python
Python fileinput模块使用实例
2015/05/28 Python
Python 创建新文件时避免覆盖已有的同名文件的解决方法
2018/11/16 Python
解决pyPdf和pyPdf2在合并pdf时出现异常的问题
2020/04/03 Python
浅析python中的del用法
2020/09/02 Python
基于Python爬取素材网站音频文件
2020/10/21 Python
美国开幕式潮店:Opening Ceremony
2018/02/10 全球购物
欧洲最古老的鞋厂:Peter Kaiser
2019/11/05 全球购物
使用Vue.js和MJML创建响应式电子邮件
2021/03/23 Vue.js
2014年公务员工作总结
2014/11/18 职场文书
Python基础数据类型tuple元组的概念与用法
2021/08/02 Python
nginx从安装到配置详细说明(安装,安全配置,防盗链,动静分离,配置 HTTPS,性能优化)
2022/02/12 Servers
SONY600GR,国产收音机厂商永远的痛
2022/04/05 无线电
Python 装饰器(decorator)常用的创建方式及解析
2022/04/24 Python