Search code examples
pythonpython-3.xwandmagickwand

wand - text wrapping - based on the image file size


Hi am trying to write text over an image. But the text overflows. Is there any way to wrap such textual content to fit inside the image?

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Image(filename='/home/path/image.jpg').clone() as img:
    print('width =', img.width)
    print('height =', img.height)
    quote = input('quote:')
    with Drawing() as draw:
        draw.font = 'wandtests/assets/League_Gothic.otf'
        draw.fill_color=Color('red')
        draw.text_alignment= 'center'
        img.font_size=50
        draw.text(int(img.width/2),int(img.height/2), quote)
        print(draw.get_font_metrics(img,quote))
        draw(img)
        print('text drawn')
    img.save(filename='/home/path/image01.jpg')

input given is:

"Success makes so many people hate you. I wish it wasn't that way. It would be wonderful to enjoy success without seeing envy in the eyes of those around you."

output image


Solution

  • A quick and dirty solution is to split the string in two pieces:

    draw.text(int(img.width/3),int(img.height/3), quote[0:len(quote)//2])
    draw.text(int(2 * img.width/3),int(2 * img.height/3), quote[len(quote)//2:-1])
    

    Splitting in 3 or more may be required if the text is still to long.