python 图形验证码的实现

python 图形验证码的实现

  • 导入pil库和ramdom库

    from PIL import Image, ImageDraw, ImageFont, ImageFilter
    import random
    
    • 1
    • 2
  • 创建画布

image1 = Image.new('RGBA', (120,60), (255,255,255,100))
  • 1
  • 创建一个画图对象
draw = ImageDraw.Draw(image1)

  • 1
  • 2
  • 声明随机颜色函数

    定义rand_color()为背景渲染的随机函数

    定义rand_num_color()为数字验证码中数字的随机颜色

    def rand_color():
    	return random.randint(100,255),random.randint(100,255),random.randint(0,255)
    def rand_num_color():
    	return random.randint(0,100),random.randint(0,155),random.randint(0,100)
    
    • 1
    • 2
    • 3
    • 4
  • 渲染背景

for x in range(0,121):
	for y in range(0,61):
		draw.point((x,y), rand_color())
  • 1
  • 2
  • 3
  • 渲染文字
font1 = ImageFont.truetype('font/bb.ttf',25)
  • 1
  • 随机生成数字
for x in range(4):
	y = random.randint(10,40)
	num = str(random.randint(0,9))
	draw.text((x*30,y),num, (rand_num_color()),font1)
  • 1
  • 2
  • 3
  • 4
  • 显示
image1.show()
  • 1

完整代码

from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 创建 空画布
image1 = Image.new('RGBA', (120,60), (255,255,255,100))

# 创建一个画画对象
draw = ImageDraw.Draw(image1)
def rand_color():
	return random.randint(100,255),random.randint(100,255),random.randint(0,255)
def rand_num_color():
	return random.randint(0,100),random.randint(0,155),random.randint(0,100)
# 渲染背景
for x in range(0,121):
	for y in range(0,61):
		draw.point((x,y), rand_color())
# 加一个渲染效果
# image1 = image1.filter(ImageFilter.BLUR)


# 渲染文字
font1 = ImageFont.truetype('font/bb.ttf',25)
# 随机生成数字
for x in range(4):
	y = random.randint(10,40)
	num = str(random.randint(0,9))
	draw.text((x*30,y),num, (rand_num_color()),font1)


# 显示保存
ima
posted @ 2020-11-27 16:33  人生的激活码  阅读(220)  评论(0编辑  收藏  举报