pillow

pip3 install pillow

创建图片

  1. from PIL import Image
  2. # 创建一张大小为120x30px的图片背景颜色为白色
  3. img = Image.new(mode='RGB', size=(120,30), color=(255,255,255))
  4. # 在图片查看器中打开
  5. img.show()
  6. # 保存图片到本地
  7. with open('code.png', 'wb') as f:
  8. img.save(f, format='png')

画笔

用于在图片上画任意的内容

  1. # 创建画笔
  2. img = Image.new(mode='RGB', size=(200,200), color=(255,255,255))
  3. draw = ImageDraw.Draw(img, mode='RGB')
  4. # 画点
  5. # param1: 坐标
  6. # param2: 颜色
  7. draw.point([10, 10], fill="red")
  8. draw.point([20, 10], fill=(0, 255, 255))
  9. # 画线
  10. # param1: 0,0 起始坐标 40,30结束坐标
  11. draw.line((0,0,40,30), fill=(255, 0, 0))
  12. # 画圆
  13. # param1: 起始坐标和结束坐标(圆要在期中间)
  14. # param2: 开始角度
  15. # param3: 结束角度
  16. draw.arc((50,50,100,100), 0, 90, fill=(255, 0, 0))
  17. # 写文本
  18. # param1: 起始坐标
  19. # param2:写入内容
  20. # param3:颜色
  21. draw.text([0,0], 'python', (255, 0, 0))
  22. # 特殊字体文字
  23. # param1: 字体文件路径
  24. # param2: 字体大小
  25. font = ImageFont.truetype("kumo.ttf", 28)
  26. draw.text([0,0], 'python', (255,0,0), font=font)

图片验证码

  1. def rm_check_code(request):
  2. from io import BytesIO
  3. from utils.random_check_code import check_code
  4. f = BytesIO()
  5. img, code = rd_check_code()
  6. img.save(f, 'png')
  7. data = f.getvalue()
  8. request.session['code'] = code
  9. return HttpResponse(data)
  1. import random
  2. from PIL import Image, ImageDraw, ImageFont, ImageFilter
  3. def check_code(width=120, height=30, char_length=5, font_file='kumo.ttf', font_size=28):
  4. code = []
  5. img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
  6. draw = ImageDraw.Draw(img, mode='RGB')
  7. def rndChar():
  8. """
  9. 生成随机字母
  10. :return:
  11. """
  12. return chr(random.randint(65, 90))
  13. def rndColor():
  14. """
  15. 生成随机颜色
  16. :return:
  17. """
  18. return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))
  19. # 写文字
  20. font = ImageFont.truetype(font_file, font_size)
  21. for i in range(char_length):
  22. char = rndChar()
  23. code.append(char)
  24. h = random.randint(0, 4)
  25. draw.text([i * width / char_length, h], char, font=font, fill=rndColor())
  26. # 写干扰点
  27. for i in range(40):
  28. draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
  29. # 写干扰圆圈
  30. for i in range(40):
  31. draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
  32. x = random.randint(0, width)
  33. y = random.randint(0, height)
  34. draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())
  35. # 画干扰线
  36. for i in range(5):
  37. x1 = random.randint(0, width)
  38. y1 = random.randint(0, height)
  39. x2 = random.randint(0, width)
  40. y2 = random.randint(0, height)
  41. draw.line((x1, y1, x2, y2), fill=rndColor())
  42. img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
  43. return img, ''.join(code)