Python PIL 减少字母间距

toa*_*ast 8 python python-imaging-library

如何减少此文本的字母间距?我想让文本更挤在一起几个像素。

我正在尝试制作一个透明的图像,上面有文字,我想把它推到一起。像这样,但透明:

图片

from PIL import Image, ImageDraw, ImageFont

(W, H) = (140, 40)

#create transparent image
image = Image.new("RGBA", (140, 40), (0,0,0,0))

#load font
font = ImageFont.truetype("Arial.ttf", 30)
draw = ImageDraw.Draw(image)

text = "kpy7n"
w,h = font.getsize(text)

draw.text(((W-w)/2,(H-h)/2), text, font=font, fill=0)

image.save("transparent-image.png")
Run Code Online (Sandbox Code Playgroud)

Orw*_*ile 7

这个功能将为您自动解决所有的痛苦。它是为了模拟 Photoshop 值而编写的,可以渲染行距(行之间的空间)以及跟踪(字符之间的空间)。

\n
def draw_text_psd_style(draw, xy, text, font, tracking=0, leading=None, **kwargs):\n    """\n    usage: draw_text_psd_style(draw, (0, 0), "Test", \n                tracking=-0.1, leading=32, fill="Blue")\n\n    Leading is measured from the baseline of one line of text to the\n    baseline of the line above it. Baseline is the invisible line on which most\n    letters\xe2\x80\x94that is, those without descenders\xe2\x80\x94sit. The default auto-leading\n    option sets the leading at 120% of the type size (for example, 12\xe2\x80\x91point\n    leading for 10\xe2\x80\x91point type).\n\n    Tracking is measured in 1/1000 em, a unit of measure that is relative to \n    the current type size. In a 6 point font, 1 em equals 6 points; \n    in a 10 point font, 1 em equals 10 points. Tracking\n    is strictly proportional to the current type size.\n    """\n    def stutter_chunk(lst, size, overlap=0, default=None):\n        for i in range(0, len(lst), size - overlap):\n            r = list(lst[i:i + size])\n            while len(r) < size:\n                r.append(default)\n            yield r\n    x, y = xy\n    font_size = font.size\n    lines = text.splitlines()\n    if leading is None:\n        leading = font.size * 1.2\n    for line in lines:\n        for a, b in stutter_chunk(line, 2, 1, \' \'):\n            w = font.getlength(a + b) - font.getlength(b)\n            # dprint("[debug] kwargs")\n            print("[debug] kwargs:{}".format(kwargs))\n                \n            draw.text((x, y), a, font=font, **kwargs)\n            x += w + (tracking / 1000) * font_size\n        y += leading\n        x = xy[0]\n\n
Run Code Online (Sandbox Code Playgroud)\n

它需要一个字体和一个绘制对象,可以通过以下方式获得:

\n
font = ImageFont.truetype("Arial.ttf", 30)\ndraw = ImageDraw.Draw(image)\n
Run Code Online (Sandbox Code Playgroud)\n


Chr*_*Chu 1

您必须逐个字符地绘制文本,然后在绘制下一个字符时更改 x 坐标

代码示例:

w,h = font.getsize("k")
draw.text(((W,H),"K", font=font, fill=0)
draw.text(((W+w)*0.7,H),"p", font=font, fill=0)
draw.text(((W+w*2)*0.7,H),"y", font=font, fill=0)
draw.text(((W+w*3)*1,H),"7", font=font, fill=0)
draw.text(((W+w*4)*0.8,H),"n", font=font, fill=0)
Run Code Online (Sandbox Code Playgroud)