How to set appropriate line width for drawing text in Python PIL?

I am trying to draw text using PIL into an image with arbitrary resolution. My current code is the result of consultations on the following two issues here and here . In both of these responses to the width textwrap.wrapwas set as such: width=40. However, with an arbitrary change in the parameters size_x, size_ythis also leads to redefinition or reduction of the image volume. Ideally, I need a way to convert the font size to pixel height and width in PIL, but I'm not sure how to do this. Here is the code that I have now:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 
import textwrap

size_x = 946 #This value can arbitrarily change
size_y = 300 #This value can arbitrarily change
font_size = 16 #This value can be adjusted to fit parameters of image if necessary

my_text = ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam scelerisque sapien convallis nisl facilisis, sed facilisis odio accumsan. Maecenas vel leo eu turpis porta dictum at vel neque. Donec sagittis felis non tellus lacinia facilisis. Vivamus vel nisi ullamcorper, feugiat lorem sagittis, pellentesque dolor. Curabitur est magna, feugiat ut nibh quis, blandit vestibulum nisl. Sed pulvinar condimentum purus et rutrum. Proin magna arcu, scelerisque at gravida ut, convallis quis orci. Mauris ipsum tortor, laoreet et leo ac, lacinia euismod tellus. Curabitur volutpat nisi a metus faucibus, vel iaculis nisl fermentum. Curabitur et orci id sapien porttitor dignissim at ac dolor. Donec nec mattis nisi. ']

tx = Image.new('RGB', (size_x, size_y),color=(255,255,255))
draw = ImageDraw.Draw(tx)

my_font = ImageFont.truetype('/Windows/Fonts/arial.ttf',size=font_size)
lines = textwrap.wrap(my_text[0], width = 130) #This width value needs to be set automatically
y_text = 0
for line in lines:
    width, height = my_font.getsize(line)
    draw.text((0, y_text), line, font = my_font, fill = (0,0,0))
    y_text += height

tx.show()

An example of an image with width=130that fills well enough.

width = 130

width=200, .

width = 200

+4
1

PIL textwrap.wrap() width, . -, , . , , , , , .

- . .

width, . , start=1, end=len(string). pivot=(end+start)/2. width=pivot, max(font.getsize(line) for line in wrapping).

  • max , , . (end=pivot)
  • width=pivot+1. , width.
  • , . (start=pivot)

, (, , , API ), , .

+4

Source: https://habr.com/ru/post/1543105/


All Articles