Python Imaging Library - Text Rendering

Python Imaging Library - Text rendering

I came up with my own solution that I find acceptable.

What I did was render the text large, like 3x the size it needs to be then scale it resize it down with antialiasing, it's not 100% perfect, but it's a hell of a lot better than default, and doesn't require cairo or pango.

for example,

image = Image.new("RGBA", (600,150), (255,255,255))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("resources/HelveticaNeueLight.ttf", fontsize)

draw.text((10, 0), txt, (0,0,0), font=font)
img_resized = image.resize((188,45), Image.ANTIALIAS)

and you endup with this result,

final result

which is a lot better than what I was getting before with the same font.

Properly render text with a given font in Python and accurately detect its boundaries

pyvips seems to do this correctly. I tried this:

$ python3
Python 3.7.3 (default, Apr 3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyvips
>>> x = pyvips.Image.text("Puzzling", dpi=300, font="Miss Fajardose", fontfile="/home/john/pics/MissFajardose-Regular.ttf")
>>> x.write_to_file("x.png")

To make:

Sample Image

The pyvips docs have a quick intro to the options:

https://libvips.github.io/pyvips/vimage.html#pyvips.Image.text

Or the C library docs have a lot more detail:

http://libvips.github.io/libvips/API/current/libvips-create.html#vips-text

It makes a one-band 8-bit image of the antialiased text which you can use for further processing, pass to NumPy or PIL, etc etc. There's a section in the intro on how to convert libvips images into arrays:

https://libvips.github.io/pyvips/intro.html#numpy-and-pil

Is there any good python library for generating and rendering text in image format?

Although nowadays I'd settle to go with web fonts and CSS,a couple of years ago I faced this problem, and put together a small project that would generate text-within a templated image on the file, according to passed URL parameters.

The project is still publicized here: https://bitbucket.org/jsbueno/dynabutton -- it is made to work as a CGI script, but could be easily adapted to work with a more eficient server (I'd recomend some security tunning as well, if you are putting it online). You can also use it to generate all your images with a server side script, and just put the resulting image files online.

(it does use PIL underneath)

Ah yes, it can do shadow, and glow with proper parameters, can use any server-installed font, and will use an image template for providing the background, so you can apply any effect manually. (the included temlates, though, are quite amateurish)

Calculate rendered text size in PIL

You can do it using the ImageFont.getsize() method. As far as I know it will handle text with embedded newlines. See example of using it in this answer of mine to another question.



Related Topics



Leave a reply



Submit