PIL-如何在文本中插入索引或下标? [英] PIL - how to insert an index, or subscript, into text?

查看:125
本文介绍了PIL-如何在文本中插入索引或下标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

赞:

计算坐标看起来不太好,也许有更好的方法吗?

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

此代码可以正常工作(),但是总是计算每个字母的索引位置很复杂.

This code works fine (), 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')

推荐答案

您可能会使用 ImageMagick 来理解 Pango标记语言,它看起来有点像像HTML.

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

生成此PNG文件:

如果要保留原始图像中文本下方的内容,请更改为-background none以在一块透明画布上书写.

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.

您还可以将所有标记放在一个单独的文本文件中,例如说"pango.txt":

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>

像这样将其传递到 ImageMagick 中:

convert pango:@pango.txt result.png 


您可以使用以下方法进行淘汰:


You could shell out and do this using:

subprocess.call()

然后,您可以轻松加载生成的图像并将其合成/粘贴到所需的位置-这大约需要3行Python,您可以将其放入函数中.

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.

这是Anthony Thyssen用 Pango 生成的图像的另一个示例,因此您可以看到一些可能性:

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

安东尼此处的 Pango 上有许多其他信息. .

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

请注意, ImageMagick 也有 Python 绑定,但我对它们并不十分熟悉,但这可能比脱壳更干净.

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.

关键字:Pango,PIL,Pillow,Python,标记,下标,上标,公式,化学公式,ImageMagick,图像,图像处理,SGML,HTML.

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

这篇关于PIL-如何在文本中插入索引或下标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆