您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

mods.py 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import Image
  2. import ImageChops
  3. import math
  4. def hex_to_color(hex):
  5. r = int(hex[0:2], 16)
  6. g = int(hex[2:4], 16)
  7. b = int(hex[4:6], 16)
  8. if len(hex) == 8:
  9. a = int(hex[6:8], 16)
  10. else:
  11. a = 255
  12. return (r, g, b, a)
  13. class BaseModification(object):
  14. def __init__(self, image, params):
  15. self._params = params
  16. self._image = image
  17. def apply(self):
  18. pass
  19. class AutotrimMod(BaseModification):
  20. def apply(self):
  21. keys = self._params.keys()
  22. if ('width' in keys or 'height' in keys) and not 'crop' in keys:
  23. if 'bgcolor' in keys:
  24. bgcolor = hex_to_color(self._params['bgcolor'])
  25. else:
  26. bgcolor = (255, 255, 255, 255)
  27. bg = Image.new(self._image.mode, self._image.size, bgcolor)
  28. diff = ImageChops.difference(self._image, bg)
  29. bbox = diff.getbbox()
  30. return self._image.crop(bbox)
  31. return self._image
  32. class CropMod(BaseModification):
  33. def apply(self):
  34. if 'crop' in self._params.keys():
  35. crop = self._params['crop']
  36. bounds = tuple(int(x) for x in crop.split(','))
  37. return self._image.crop(bounds)
  38. return self._image
  39. class ResizeMod(BaseModification):
  40. def apply(self):
  41. keys = self._params.keys()
  42. if 'width' in keys or 'height' in keys:
  43. w = self._params.get('width', None)
  44. h = self._params.get('height', None)
  45. target_w = float(w) if w else None
  46. target_h = float(h) if h else None
  47. source_w, source_h = [float(v) for v in self._image.size]
  48. scale = 1.0
  49. if target_w:
  50. temp_scale = target_w / source_w
  51. if temp_scale < scale:
  52. scale = temp_scale
  53. if target_h:
  54. temp_scale = target_h / source_h
  55. if temp_scale < scale:
  56. scale = temp_scale
  57. if scale < 1.0:
  58. new_size = (int(round(source_w * scale)),
  59. int(round(source_h * scale)))
  60. self._image = self._image.resize(new_size, Image.ANTIALIAS)
  61. new_w = int(target_w if target_w else self._image.size[0])
  62. new_h = int(target_h if target_h else self._image.size[1])
  63. if 'bgcolor' in keys:
  64. bgcolor = hex_to_color(self._params['bgcolor'])
  65. else:
  66. bgcolor = (255, 255, 255, 255)
  67. bg = Image.new(self._image.mode, (new_w, new_h), bgcolor)
  68. left = int(math.floor(float(new_w - self._image.size[0]) / 2))
  69. top = int(math.floor(float(new_h - self._image.size[1]) / 2))
  70. bg.paste(self._image, (left, top))
  71. return bg
  72. return self._image