You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.3 KiB

  1. # Copyright 2019 Alexandre Díaz <dev@redneboa.es>
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  3. import base64
  4. import math
  5. from PIL import Image
  6. from io import BytesIO
  7. def n_rgb_to_hex(_r, _g, _b):
  8. return '#%02x%02x%02x' % (int(255*_r), int(255*_g), int(255*_b))
  9. def convert_to_image(field_binary):
  10. return Image.open(BytesIO(base64.b64decode(field_binary)))
  11. def image_to_rgb(img):
  12. def normalize_vec3(vec3):
  13. _l = 1.0 / math.sqrt(vec3[0]*vec3[0]
  14. + vec3[1]*vec3[1]
  15. + vec3[2]*vec3[2])
  16. return (vec3[0]*_l, vec3[1]*_l, vec3[2]*_l)
  17. # Force Alpha Channel
  18. if img.mode != 'RGBA':
  19. img = img.convert('RGBA')
  20. width, height = img.size
  21. # Reduce pixels
  22. width, height = (max(1, int(width/4)), max(1, int(height/4)))
  23. img = img.resize((width, height))
  24. rgb_sum = [0, 0, 0]
  25. # Mix. image colors using addition method
  26. RGBA_WHITE = (255, 255, 255, 255)
  27. for i in range(0, height*width):
  28. rgba = img.getpixel((i % width, i / width))
  29. if rgba[3] > 128 and rgba != RGBA_WHITE:
  30. rgb_sum[0] += rgba[0]
  31. rgb_sum[1] += rgba[1]
  32. rgb_sum[2] += rgba[2]
  33. _r, _g, _b = normalize_vec3(rgb_sum)
  34. return (_r, _g, _b)