use_pil_draw.py 957 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from PIL import Image, ImageDraw, ImageFont, ImageFilter
  4. import random
  5. # 随机字母:
  6. def rndChar():
  7. return chr(random.randint(65, 90))
  8. # 随机颜色1:
  9. def rndColor():
  10. return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
  11. # 随机颜色2:
  12. def rndColor2():
  13. return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
  14. # 240 x 60:
  15. width = 60 * 4
  16. height = 60
  17. image = Image.new('RGB', (width, height), (255, 255, 255))
  18. # 创建Font对象:
  19. font = ImageFont.truetype('Arial.ttf', 36)
  20. # 创建Draw对象:
  21. draw = ImageDraw.Draw(image)
  22. # 填充每个像素:
  23. for x in range(width):
  24. for y in range(height):
  25. draw.point((x, y), fill=rndColor())
  26. # 输出文字:
  27. for t in range(4):
  28. draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
  29. # 模糊:
  30. image = image.filter(ImageFilter.BLUR)
  31. image.save('code.jpg', 'jpeg')