dynamic.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import os
  2. from importlib import import_module
  3. from PIL import Image, ImageColor, ImageDraw, ImageFont
  4. from misago.conf import settings
  5. from . import store
  6. COLOR_WHEEL = (
  7. '#d32f2f', '#c2185b', '#7b1fa2', '#512da8', '#303f9f', '#1976d2', '#0288D1', '#0288d1',
  8. '#0097a7', '#00796b', '#388e3c', '#689f38', '#afb42b', '#fbc02d', '#ffa000', '#f57c00',
  9. '#e64a19',
  10. )
  11. COLOR_WHEEL_LEN = len(COLOR_WHEEL)
  12. FONT_FILE = os.path.join(os.path.dirname(__file__), 'font.ttf')
  13. def set_avatar(user):
  14. name_bits = settings.MISAGO_DYNAMIC_AVATAR_DRAWER.split('.')
  15. drawer_module = '.'.join(name_bits[:-1])
  16. drawer_module = import_module(drawer_module)
  17. drawer_function = getattr(drawer_module, name_bits[-1])
  18. image = drawer_function(user)
  19. store.store_new_avatar(user, image)
  20. def draw_default(user):
  21. """default avatar drawer that draws username's first letter on color"""
  22. image_size = max(settings.MISAGO_AVATARS_SIZES)
  23. image = Image.new("RGBA", (image_size, image_size), 0)
  24. image = draw_avatar_bg(user, image)
  25. image = draw_avatar_flavour(user, image)
  26. return image
  27. def draw_avatar_bg(user, image):
  28. image_size = image.size
  29. color_index = user.pk - COLOR_WHEEL_LEN * (user.pk // COLOR_WHEEL_LEN)
  30. main_color = COLOR_WHEEL[color_index]
  31. rgb = ImageColor.getrgb(main_color)
  32. bg_drawer = ImageDraw.Draw(image)
  33. bg_drawer.rectangle([(0, 0), image_size], rgb)
  34. return image
  35. def draw_avatar_flavour(user, image):
  36. string = user.username[0]
  37. image_size = image.size[0]
  38. size = int(image_size * 0.7)
  39. font = ImageFont.truetype(FONT_FILE, size=size)
  40. text_size = font.getsize(string)
  41. text_pos = ((image_size - text_size[0]) / 2, (image_size - text_size[1]) / 2, )
  42. writer = ImageDraw.Draw(image)
  43. writer.text(text_pos, string, font=font)
  44. return image