user1387717
user1387717

Reputation: 1049

Write Text to Image with Max Width in Pixels Python PIL

There is a similar question to mine here: python PIL draw multiline text on image

However, the solution uses:

textwrap.wrap(..., width=40)

Which is the width in characters. I'm trying to do something where the width should be in pixels and all the docs seem to only have the width in chars. (I'll have different size texts so that character width won't be constant for a certain width image)

Upvotes: 4

Views: 3809

Answers (2)

bigzbig
bigzbig

Reputation: 399

My simple solution:

def wrap_text(text, width, font):
    text_lines = []
    text_line = []
    text = text.replace('\n', ' [br] ')
    words = text.split()
    font_size = font.getsize(text)

    for word in words:
        if word == '[br]':
            text_lines.append(' '.join(text_line))
            text_line = []
            continue
        text_line.append(word)
        w, h = font.getsize(' '.join(text_line))
        if w > width:
            text_line.pop()
            text_lines.append(' '.join(text_line))
            text_line = [word]

    if len(text_line) > 0:
        text_lines.append(' '.join(text_line))

    return text_lines

Upvotes: 4

Jacinto
Jacinto

Reputation: 180

I try to find something like you say, but i don't find anything, so i create my own method. font.getsize(TEXT) return the width and the height in pixels of the TEXT, so my method splits the string in words, and verify if the word is greater than the width of the image, if not i concatenate the word in a variable. when this variable is greater than the image width i append into a list and clear the variable, so i verify the next line.

Upvotes: 1

Related Questions