Discuss / Python / PIL

儒生脱尘

#1 Created at ... [Delete] [Delete and Lock User]

验证码文字旋转,添加随机线条

预览: https://imgsa.baidu.com/forum/w%3D580/sign=553ba19d00f79052ef1f47363cf2d738/f6baca0735fae6cd0e1679ef06b30f2443a70f2b.jpg

from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random
def rndChar():
    return chr(random.randint(65,90))#根据随机ascii码,返回对应字符
def rndColor():
    return (random.randint(64,255),random.randint(64,255),random.randint(64,255))#返回随机颜色
def rndColor2():
    return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
def line():
    return (random.random()*240,random.random()*60,random.random()*240,random.random()*60)#返回一个随机tuple
img=Image.new('RGBA',(240,60),(255,255,255))#创建图片,尺寸240x60,颜色模式RGB,填充色纯白色
font=ImageFont.truetype('C:\\Windows\\Fonts\\DAUPHINN.TTF',36)#设置字体的类型,font-family和font-size
draw=ImageDraw.Draw(img)#新建一个画板实例,传入参数刚刚创建的img对象作为画板
for x in range(0,img.size[0],2):#画板添加杂色
    for y in range(0,img.size[1]):
        draw.point((x,y),fill=rndColor())
for i in range(4):
    img1=Image.new('RGBA',(55,55),(255,255,255,0))#新建一个透明图片img1
    img_font=ImageDraw.Draw(img1)#img1作为画板
    img_font.text((15,8),rndChar(),font=font,fill=rndColor2())#img1上写字
    img1=img1.rotate(random.randint(-30,30))#img1旋转
    img.paste(img1,(10+i*60,10),mask=img1)#把img1粘贴到img上面
draw.line(line(),rndColor2())#添加干扰杂线
draw.line(line(),rndColor2())
draw.line(line(),rndColor2())
draw.line(line(),rndColor2())
img.show()#预览img

兄弟用心了 哈哈 这么喜欢PIL?

  • 尝试了各种方法也没解决,安装不了!!,求指教

Exception: Traceback (most recent call last): File "c:\program files (x86)\python36-32\lib\site-packages\pip\compat__init.py", line 73, in console_to_str return s.decode(sys.stdout__.encoding) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position 88: invalid start byte

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "c:\program files (x86)\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files (x86)\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\program files (x86)\python36-32\lib\site-packages\pip\req\req_install.py", line 878, in install spinner=spinner, File "c:\program files (x86)\python36-32\lib\site-packages\pip\utils__init.py", line 676, in call_subprocess line = console_to_str(proc.stdout.readline()) File "c:\program files (x86)\python36-32\lib\site-packages\pip\compat\init__.py", line 76, in console_to_str return s.decode('utf_8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position 88: invalid start byte


  • 1

Reply