Python练手项目0010

本项目采用的是https://github.com/Yixiaohan/show-me-the-code中所提供的练习项目,所有代码均为原创,转载请注明,谢谢。


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



# -*- coding: utf-8 -*-

"""
Created on Wed Jan 11 12:48:02 2017


@author: sky
"""


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


IMAGE_MODE = 'RGB'
IMAGE_BG_COLOR = (255,255,255)
Image_Font = 'arial.ttf'
chars = string.letters + string.digits
text = ''.join(random.sample(chars,10))


def colorRandom():
    return (random.randint(32,127),random.randint(32,127),random.randint(32,127))




#change 噪点频率(%)
def create_identifying_code(strs, width=1080, height=800, chance=2):
    im = Image.new(IMAGE_MODE, (width, height), IMAGE_BG_COLOR)
    draw = ImageDraw.Draw(im)
    #绘制背景噪点
    for w in xrange(width):
        for h in xrange(height):
            if chance < random.randint(1, 100):
                draw.point((w, h), fill=colorRandom())


    font = ImageFont.truetype(Image_Font, 100)
    font_width, font_height = font.getsize(strs)
    strs_len = len(strs)
    x = (width - font_width)/2
    y = (height - font_height)/2
    #逐个绘制文字
    for i in strs:
        draw.text((x,y), i, colorRandom(), font)
        x += font_width/strs_len
    #模糊
    im = im.filter(ImageFilter.BLUR)
    im.save('identifying_code_pic.jpg') 




if __name__ == '__main__':

    create_identifying_code(text)


详细代码和结果,可以参考https://github.com/g8015108/exercise-for-python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值