Difference between Pillow textsize() and SVG rende

2019-08-20 14:09发布

I am trying to "predict" a python-generated svg text size, using pillow and textsize().

Here is a sample SVG :

<svg width="200" height="30" xmlns="http://www.w3.org/2000/svg">
  <style>
    .label {
      color: black; 
      font: 14pt 'Inconsolata'; 
    }
  </style>
  <text x="0" y="20" class="label">
    I love SVG!
  </text>
</svg>

The result seems to be 102.64 x 19 (according to Chromium-based browsers) : enter image description here

But, trying to get the same result with pillow, the result is quite different :

from PIL import Image, ImageFont, ImageDraw

txt = "I love SVG!"
font = ImageFont.truetype("C:\\Windows\\Fonts\\Inconsolata.otf", 14)
img = Image.new('RGB', (150, 30), color = (73, 109, 137))
draw_txt = ImageDraw.Draw(img)
width, height = draw_txt.textsize(txt, font=font)
print(f"Text size for \"{txt}\" = {width} x {height}")

Text size for "I love SVG!" = 154px x 25px

I was expecting some differences, but not that much, why is that ?

I suspect unit type issues, but pt to px convertion is done well in the SVG, and on the pillow side, ImageFont constructor specify that the input size is in points, and textsize() output is supposed to be in pixels.


Note : For this example purpose, I am using the Inconsolata font, which you can download [here] if you want to run the above python script.

0条回答
登录 后发表回答