PIL - how to insert an index, or subscript, into t

2019-08-02 04:47发布

Like this: enter image description here

Calculating coordinates looks not so good, maybe there is a better way?

This code works fine (enter image description here), but it's complicated always calculate where to place index for each letter.

image = Image.new('I', (300, 100), "white").convert('RGBA')
font = ImageFont.truetype(font=r"C:\Windows\Fonts\Arial.ttf", size=39)
draw = ImageDraw.Draw(image, 'RGBA')

draw.text((10, 10), "P", fill="black", font=font, align="center")

font = ImageFont.truetype(font=r"C:\Windows\Fonts\Arial.ttf", size=20)
draw.text((25, 35), "2", fill="black", font=font, align="center")

image.save(output_folder + 'test.png')

1条回答
乱世女痞
2楼-- · 2019-08-02 05:26

One possibility for you might be to use ImageMagick which understands Pango Markup Language - which looks kind of like HTML.

So, at the command-line you could run this:

convert -background white pango:'<span size="49152">Formula: <b>2P<sub><small><small>2</small></small></sub>O<sub><small><small>5</small></small></sub></b></span>' formula.png

which produces this PNG file:

enter image description here

Change to -background none to write on a piece of transparent canvas if you want to preserve whatever is underneath the text in your original image.

You can also put all the markup in a separate text file, called say "pango.txt" like this:

<span size="49152">Formula: <b>2P<sub><small><small>2</small></small></sub>O<sub><small><small>5</small></small></sub></b></span>

and pass that into ImageMagick like this:

convert pango:@pango.txt result.png 

You could shell out and do this using:

subprocess.call()

Then you can easily load the resultant image and composite/paste it in where you want it - that would take about 3 lines of Python that you could put in a function.


Here is a further example of an image generated with Pango by Anthony Thyssen so you can see some of the possibilities:

enter image description here

There is loads of further information on Pango by Anthony here.


Note that there are also Python bindings for ImageMagick but I am not very familiar with them, but that may be cleaner than shelling out.

Keywords: Pango, PIL, Pillow, Python, markup, subscript, superscript, formula, chemical formulae, ImageMagick, image, image processing, SGML, HTML.

查看更多
登录 后发表回答