python基础-第三方模块PIL_绘图,验证码
PIL:Python Imaging Library,Python平台上图像处理标准库,L功能非常强大,API简单易用.
一、安装PIL
可通过 easy_install 、 pip、PIL官方网站下载exe安装包等方法安装
二、图像操作
1、缩放操作:
>>> import Image >>> im = Image.open('C:\Users\wcc\Desktop\devushka-vzglyad-lico-golovnoy.jpg') >>> w,h = im.size >>> im.thumbnail((w//2,h//2)) #缩小 >>> im.save('C:\Users\wcc\Desktop\devushka-vzglyad-lico-golovnoysss.jpg')
2、模糊效果:
>>> import Image >>> import ImageFilter >>> im2 = im.filter(ImageFilter.BLUR) >>> im2.save('C:\Users\wcc\Desktop\devushka-vzglyad-lico-golovnoyaaa.jpg') >>>
3、绘图操作,生成验证码:
#!/usr/bin/env python #coding:utf-8 import Image,ImageDraw,ImageFont,ImageFilter import random #随机字母: def rndChar(): return chr(random.randint(65,90)) #随机颜色1: def rndColor(): return (random.randint(64,255),random.randint(64,255),random.randint(64,255)) #240 x 60: width = 60 * 4 heigh = 60 image = Image.new('RGB',(width,heigh),(255,255,255)) #创建font对象: font = ImageFont.truetype('Arial.ttf',36) #创建Draw对象: draw = ImageDraw.Draw(image) for x in range(width): for y in range(heigh): draw.point((x,y),fill=rndColor()) #输出文字: for t in range(4): draw.text((60 * t + 10,10),rndChar(),font=font,fill=rndColor()) #模糊: image = image.filter(ImageFilter.BLUR) image.save('code.jpg','jpeg')
效果图如下:
详细了解PIL的强大功能,请请参考PIL官方文档