python 利用 PIL 生成随机验证码图片【附:使用DOS命令更换pip下载源】
声明:PIL资料来自博客园,详细资料请点击 https://www.cnblogs.com/fu-yong/p/8811851.html
一、验证码图片样式:
二、模块
- PIL (需要安装,使用命令: pip install pillow)
- random
三、代码
更换路径后可以直接使用
from PIL import Image,ImageFont,ImageDraw
import random
#用于生成随机的颜色值的函数
def getRandomColor():
c1 = random.randint(0,255)
c2 = random.randint(0,255)
c3 = random.randint(0,255)
return (c1,c2,c3)
#用于生成随机的字符串的函数
def getRandomStr():
random_num = str(random.randint(0,9)) #获取随机的数字0-9
random_low_letter = chr(random.randint(97,122)) #获取随机的小写字母a-z
random_upper_letter = chr(random.randint(65,90))#获取随机的大写字母A-Z
#利用random,choice()方法获取三个值中的某一个
random_char = random.choice([random_num,random_low_letter,random_upper_letter])
return random_char
#创建一个图片对象,参数是:RGB模式,图片宽高,颜色值
image = Image.new('RGB',(150,30),getRandomColor())
draw = ImageDraw.Draw(image) #获取一个画笔对象,传入创建的图片对象
#创建一个图片字体对象,参数是:字体格式,字体大小
#注:注意字体的安装目录,可以直接在python的安装目录下搜索:ttf
font = ImageFont.truetype(r'C:\python\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\cmmi10.ttf',size=25)
#循环5次写入字符到图片
for i in range(5):
random_char = getRandomStr()
#在图片上写入得到的随机字符串,参数是:位置,字符串,颜色,字体格式
draw.text((10 + i * 30,0),random_char,getRandomColor(),font=font)
width = 150
height = 30
# 设置图片噪线
for i in range(5):
x1 = random.randint(0,width)
x2 = random.randint(0,width)
y1 = random.randint(0,height)
y2 = random.randint(0,height)
draw.line((x1,y1,x2,y2),fill=getRandomColor())
# 设置图片噪点
for i in range(5):
draw.point([random.randint(0,width),random.randint(0,height)],fill=getRandomColor())
x = random.randint(0,width)
y = random.randint(0,height)
draw.arc((x,y,x + 4,y + 4),0,90,fill=getRandomColor())
#写入保存图片,参数是:open()函数传入对应的路径和图片名称,保存图片格式
image.save(open(r'D:\Coding\randomCode.png','wb'),'png')
四、python pip更换下载源
1、部分国内常用下载源:
清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
豆瓣:http://pypi.douban.com/simple/
2、使用下载源下载:
pip install -i 包名 http://pypi.douban.com/simple/
3、一劳永逸使用国内源下载:
pip config set global.index-url 国内镜像地址
如:
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
还没有评论,来说两句吧...