Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. from PIL import Image, ImageFont, ImageDraw
  2.  
  3.  
  4. def draw_text(draw, x, y, text, font):
  5. shadowcolor = (0, 0, 0)
  6. fillcolor = (255, 255, 255)
  7. # thin border
  8. draw.text((x - 1, y), text, font=font, fill=shadowcolor)
  9. draw.text((x + 1, y), text, font=font, fill=shadowcolor)
  10. draw.text((x, y - 1), text, font=font, fill=shadowcolor)
  11. draw.text((x, y + 1), text, font=font, fill=shadowcolor)
  12.  
  13. # thicker border
  14. draw.text((x - 1, y - 1), text, font=font, fill=shadowcolor)
  15. draw.text((x + 1, y - 1), text, font=font, fill=shadowcolor)
  16. draw.text((x - 1, y + 1), text, font=font, fill=shadowcolor)
  17. draw.text((x + 1, y + 1), text, font=font, fill=shadowcolor)
  18.  
  19. # now draw the text over it
  20. draw.text((x, y), text, font=font, fill=fillcolor)
  21.  
  22.  
  23. def write_text(image_path, text, font_type='this.ttf'):
  24. text = text
  25. in_path = image_path
  26. out_path = image_path
  27.  
  28. img = Image.open(in_path)
  29. img_drawer = ImageDraw.Draw(img)
  30. width, height = img.size
  31. text_array = text.split()
  32. size = height // 7
  33. font = ImageFont.truetype(font_type, size)
  34. text_length = font.getsize(text)[0] / 2
  35. x0 = 0
  36. i = 0
  37. while x0 <= text_length:
  38. x0 += font.getsize(text_array[i])[0]
  39. i += 1
  40. i -= 1
  41. upper_text = ' '.join(text_array[:i])
  42. bottom_text = ' '.join(text_array[i:])
  43. x0 = font.getsize(upper_text)[0]
  44. x1, y0 = font.getsize(bottom_text)
  45. max_x = max(x0, x1)
  46. k = max_x / width * 1.1
  47. if k >= 1:
  48. size = size // k
  49. font = ImageFont.truetype(font_type, int(size))
  50. x0, y0 = font.getsize(upper_text)
  51. x1 = font.getsize(bottom_text)[0]
  52. upper_x = (width - x0) / 2
  53. bottom_x = (width - x1) / 2
  54. y = height / 30
  55. draw_text(img_drawer, upper_x, y, upper_text, font)
  56. draw_text(img_drawer, bottom_x, height - y - y0, bottom_text, font)
  57. img.save(out_path)
  58. img.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement