码迷,mamicode.com
首页 > 编程语言 > 详细

【python小练】0010

时间:2016-03-28 02:17:21      阅读:440      评论:0      收藏:0      [点我收藏+]

标签:

第 0010 题:使用 Python 生成类似于下图中的字母验证码图片

技术分享

 

 

思路:

1. 随机生成字符串

2. 创建画布往上头写字符串

3. 干扰画面

 

 

code:

# codeing: utf-8

from PIL import Image, ImageDraw, ImageFont, ImageFilter
import string
import random


def get4char():
    return [random.choice(string.ascii_letters) for _ in range(4)]  # 可以把‘_’换做任意字母,‘_’说明后续不用


def getcolor():
    return random.randint(30, 100), random.randint(30, 100), random.randint(30, 100)


def getpicture():
    width = 240
    height = 60

    image = Image.new(RGB, (width, height), (180, 180, 180))
    font = ImageFont.truetype(arial.ttf, 40)

    draw = ImageDraw.Draw(image)
    code = get4char()
    for ch in range(4):
        draw.text((60 * ch,30), code[ch], font=font, fill=getcolor())

    for _ in range(random.randint(1500, 3000)):
        draw.point((random.randint(0, width), random.randint(0, height)), fill=getcolor())

    image = image.filter(ImageFilter.BLUR)
    image.save("".join(code) + .jpg)


getpicture()

 

Notes:

1. string.ascii_letters,大小写英文字母集合字符串

2. random.choice():Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

3. random.randint():Return a random integer N such that <= <= b. Alias for randrange(a, b+1).

4. image.new(‘RGB‘, (w,h), (r,g,b))

 

result:

技术分享

技术分享

技术分享

 

 

我觉得自己应该去把tutorial从头到尾先看一遍= - =

下一篇写怎么识别验证码咯。

 

【python小练】0010

标签:

原文地址:http://www.cnblogs.com/liez/p/5327577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!