title: How to set appropriate line width for drawing text in Python PIL?
body: <p>I am trying to draw text using PIL into an image with arbitrary resolution. My current code is a result of consulting the following two questions <a href="https://stackoverflow.com/questions/8257147/wrap-text-in-pil">here</a> and <a href="https://stackoverflow.com/questions/7698231/python-pil-draw-multiline-text-on-image">here</a>. In both of these answers, the width value for <code>textwrap.wrap</code> was set as such: <code>width=40</code>. However, with arbitrarily changing parameters <code>size_x</code> and <code>size_y</code> this results in overfitting or underfitting the scope of image. Ideally, I would need a way to convert the size of the font into height and width pixel values in PIL but I am unsure how to do it. Here is the code as I have it now:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>Example image with <code>width=130</code> which is filling fairly well.</p>
  
  <p><img src="https://i.stack.imgur.com/Mo0RW.png" alt="width = 130"></p>
  
  <p>Example image with <code>width=200</code> which is overfilling.</p>
  
  <p><img src="https://i.stack.imgur.com/BgqWB.png" alt="width = 200"></p>