[Python] python通过pil生成图片验证码 →→→→→进入此内容的聊天室

来自 , 2020-08-07, 写在 Python, 查看 132 次.
URL http://www.code666.cn/view/587b7b83
  1. # -*- coding: utf-8 -*-
  2. #导入三个模块
  3. import Image,ImageDraw,ImageFont
  4. import random
  5. import math
  6. '''基本功能'''
  7. #图片宽度
  8. width = 100
  9. #图片高度
  10. height = 40
  11. #背景颜色
  12. bgcolor = (255,255,255)
  13. #生成背景图片
  14. image = Image.new('RGB',(width,height),bgcolor)
  15. #加载字体
  16. font = ImageFont.truetype('FreeSans.ttf',30)
  17. #字体颜色
  18. fontcolor = (0,0,0)
  19. #产生draw对象,draw是一些算法的集合
  20. draw = ImageDraw.Draw(image)
  21. #画字体,(0,0)是起始位置
  22. draw.text((0,0),'1234',font=font,fill=fontcolor)
  23. #释放draw
  24. del draw
  25. #保存原始版本
  26. image.save('1234_1.jpeg')
  27. '''演示扭曲,需要新建一个图片对象'''
  28. #新图片
  29. newImage = Image.new('RGB',(width,height),bgcolor)
  30. #load像素
  31. newPix = newImage.load()
  32. pix = image.load()
  33. offset = 0
  34. for y in range(0,height):
  35.     offset += 1
  36.     for x in range(0,width):
  37.         #新的x坐标点
  38.         newx = x + offset
  39.         #你可以试试如下的效果
  40.         #newx = x + math.sin(float(y)/10)*10
  41.         if newx < width:                        
  42.             #把源像素通过偏移到新的像素点
  43.             newPix[newx,y] = pix[x,y]
  44. #保存扭曲后的版本            
  45. newImage.save('1234_2.jpeg')
  46. '''形变一下'''
  47. #x1 = ax+by+c
  48. #y1 = dx+ey+f
  49. newImage = image.transform((width+30,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0))
  50. newImage.save('1234_3.jpeg')
  51. '''画干扰线,别画太多,免得用户都看不清楚'''        
  52. #创建draw,画线用
  53. draw = ImageDraw.Draw(newImage)
  54. #线的颜色
  55. linecolor= (0,0,0)
  56. for i in range(0,15):
  57.     #都是随机的
  58.     x1 = random.randint(0,width)
  59.     x2 = random.randint(0,width)
  60.     y1 = random.randint(0,height)
  61.     y2 = random.randint(0,height)
  62.     draw.line([(x1, y1), (x2, y2)], linecolor)            
  63.            
  64. #保存到本地
  65. newImage.save('1234_4.jpeg')
  66.  
  67. #//python/7368

回复 "python通过pil生成图片验证码"

这儿你可以回复上面这条便签

captcha