Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. class ImageGen:
  2. def __init__(self, img_path, font_path, font_size=21):
  3. self.img = Image.open(os.path.join(img_path))
  4. self.font = ImageFont.truetype(font_path, font_size)
  5. self.text = ""
  6. self._img_size = self.img.size
  7. self.draw = ImageDraw.Draw(self.img)
  8.  
  9. @property
  10. def img_size(self):
  11. return self._img_size
  12.  
  13. def gen_text(self, start_pos, end_pos):
  14. Rus = RussianDictionary()
  15. from random import randint
  16. num = randint(start_pos,end_pos)
  17. sentense = list()
  18. for i in range(num):
  19. sentense.append(Rus.get_random_word())
  20. self.text = " ".join(sentense)
  21.  
  22. def _start_pos(self, width):
  23.  
  24. lines = textwrap.wrap(self.text, width)
  25. _, y = self.draw.textsize(self.text, font=self.font)
  26. max_width, max_height = 0,0
  27. for line in lines:
  28. width, height = draw.textsize(line, font=self.font)
  29. if width > max_width:
  30. max_width = width
  31. if height > max_height:
  32. max_height = height
  33.  
  34. x = randint(1, self.img_size - max_width)
  35. y = randint(1, self.img_size - y*len(lines))
  36. return x,y
  37.  
  38. def make_text_border(self, pos):
  39. positions = [list(C_((tmp, pos[1] - 1, pos[1], pos[1] + 1), 2))[:3]
  40. for tmp in [pos[0] - 1,pos[0],pos[0] + 1]]
  41. for i in positions:
  42. for q in i:
  43. self.draw.text(q, self.text, (0,0,0), font=self.font)
  44.  
  45. def gen_image(self):
  46. lines = textwrap.wrap(self.text, width=25)
  47. x_text, y_text = self._start_pos(25)
  48. for line in lines:
  49. width, height = self.draw.textsize(line, font=self.font)
  50. make_text_border((x_text , y_text))
  51. self.draw.text((x_text , y_text), line, font=self.font)
  52. y_text += height
  53.  
  54. def save_image(self, path, name):
  55. self.img.save(os.path.join(path, name))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement