Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from PIL import Image, ImageFont, ImageDraw
- def draw_text(draw, x, y, text, font):
- shadowcolor = (0, 0, 0)
- fillcolor = (255, 255, 255)
- # thin border
- draw.text((x - 1, y), text, font=font, fill=shadowcolor)
- draw.text((x + 1, y), text, font=font, fill=shadowcolor)
- draw.text((x, y - 1), text, font=font, fill=shadowcolor)
- draw.text((x, y + 1), text, font=font, fill=shadowcolor)
- # thicker border
- draw.text((x - 1, y - 1), text, font=font, fill=shadowcolor)
- draw.text((x + 1, y - 1), text, font=font, fill=shadowcolor)
- draw.text((x - 1, y + 1), text, font=font, fill=shadowcolor)
- draw.text((x + 1, y + 1), text, font=font, fill=shadowcolor)
- # now draw the text over it
- draw.text((x, y), text, font=font, fill=fillcolor)
- def write_text(image_path, text, font_type='this.ttf'):
- text = text
- in_path = image_path
- out_path = image_path
- img = Image.open(in_path)
- img_drawer = ImageDraw.Draw(img)
- width, height = img.size
- text_array = text.split()
- size = height // 7
- font = ImageFont.truetype(font_type, size)
- text_length = font.getsize(text)[0] / 2
- x0 = 0
- i = 0
- while x0 <= text_length:
- x0 += font.getsize(text_array[i])[0]
- i += 1
- i -= 1
- upper_text = ' '.join(text_array[:i])
- bottom_text = ' '.join(text_array[i:])
- x0 = font.getsize(upper_text)[0]
- x1, y0 = font.getsize(bottom_text)
- max_x = max(x0, x1)
- k = max_x / width * 1.1
- if k >= 1:
- size = size // k
- font = ImageFont.truetype(font_type, int(size))
- x0, y0 = font.getsize(upper_text)
- x1 = font.getsize(bottom_text)[0]
- upper_x = (width - x0) / 2
- bottom_x = (width - x1) / 2
- y = height / 30
- draw_text(img_drawer, upper_x, y, upper_text, font)
- draw_text(img_drawer, bottom_x, height - y - y0, bottom_text, font)
- img.save(out_path)
- img.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement