dynamic.py 1.7 KB

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