无法使用 Pillow 和 Python 将角色居中
Can't center characters using Pillow and Python
我正在尝试在图像的特定位置写入字符。我正在使用 Pillow v6,Python 3.6.
这是我的代码,我一个字符一个字符地绘制,传递我计算的左上角。
font = ImageFont.truetype('platechar.tff', 500)
def draw_single_char(img, font, val, tl): #tl = (x,y)
pil_img = Image.fromarray(np.uint8(img))
draw = ImageDraw.Draw(pil_img)
draw.text(tl, val, (0,0,0), font=font)
img = np.array(pil_img)
return img
输出没有居中,我从字体中得到了字符的宽度和高度,然后用我的左上角绘制了包含字符的矩形。字符未在矩形内居中。
字体:https://drive.google.com/open?id=1N9rN-AgjK83U9ZDycLKxjeMP3o36vbfg
我想要这样(另一种字体)
编辑
使用 Bidu Font editor 我能够删除水平 space (蓝线)。我怎样才能垂直居中?
到目前为止的结果...
看起来您使用的字体原本包含非居中数字。所以你应该选择另一种字体或者你可以在一个特殊的字体编辑器中修改你的placechar.tff
。
您还可以手动计算每个符号的坐标偏移量,将它们存储到字典中并在绘制前将其应用于您的文本。这看起来不是个好主意,但它也可以。
计算要绘制的文本的宽度和高度:
from PIL import Image, ImageDraw, ImageFont
txt='7'
font = ImageFont.truetype('platechar.ttf', 250)
(W, H) = font.getsize(txt)
image = Image.new('RGB', (256, 256), (63, 63, 63, 0))
drawer = ImageDraw.Draw(image)
(offset_w, offset_h) = font.getoffset(txt)
(x, y, W_mask, H_mask) = font.getmask(txt).getbbox()
drawer.text((10, 10 - offset_h), txt, align='center', font=font)
drawer.rectangle((10, 10, W + offset_w, 10 + H - offset_h), outline='black')
drawer.rectangle((x+10, y+10, W_mask+10, H_mask+10), outline='red')
image.show()
image.save('example.png', 'PNG')
采用@Fomalhaut 建议的路径后,使用字体编辑器。我找到了 Bidu 字体编辑器(问题中的link)。我能够修复水平 space (也显示在问题中)。对于垂直 space,在搜索菜单后,我找到了更改 ascent
的设置选项。
我把它降低到 1440,它起作用了。
我正在尝试在图像的特定位置写入字符。我正在使用 Pillow v6,Python 3.6.
这是我的代码,我一个字符一个字符地绘制,传递我计算的左上角。
font = ImageFont.truetype('platechar.tff', 500)
def draw_single_char(img, font, val, tl): #tl = (x,y)
pil_img = Image.fromarray(np.uint8(img))
draw = ImageDraw.Draw(pil_img)
draw.text(tl, val, (0,0,0), font=font)
img = np.array(pil_img)
return img
输出没有居中,我从字体中得到了字符的宽度和高度,然后用我的左上角绘制了包含字符的矩形。字符未在矩形内居中。
字体:https://drive.google.com/open?id=1N9rN-AgjK83U9ZDycLKxjeMP3o36vbfg
我想要这样(另一种字体)
编辑
使用 Bidu Font editor 我能够删除水平 space (蓝线)。我怎样才能垂直居中?
到目前为止的结果...
看起来您使用的字体原本包含非居中数字。所以你应该选择另一种字体或者你可以在一个特殊的字体编辑器中修改你的placechar.tff
。
您还可以手动计算每个符号的坐标偏移量,将它们存储到字典中并在绘制前将其应用于您的文本。这看起来不是个好主意,但它也可以。
计算要绘制的文本的宽度和高度:
from PIL import Image, ImageDraw, ImageFont
txt='7'
font = ImageFont.truetype('platechar.ttf', 250)
(W, H) = font.getsize(txt)
image = Image.new('RGB', (256, 256), (63, 63, 63, 0))
drawer = ImageDraw.Draw(image)
(offset_w, offset_h) = font.getoffset(txt)
(x, y, W_mask, H_mask) = font.getmask(txt).getbbox()
drawer.text((10, 10 - offset_h), txt, align='center', font=font)
drawer.rectangle((10, 10, W + offset_w, 10 + H - offset_h), outline='black')
drawer.rectangle((x+10, y+10, W_mask+10, H_mask+10), outline='red')
image.show()
image.save('example.png', 'PNG')
采用@Fomalhaut 建议的路径后,使用字体编辑器。我找到了 Bidu 字体编辑器(问题中的link)。我能够修复水平 space (也显示在问题中)。对于垂直 space,在搜索菜单后,我找到了更改 ascent
的设置选项。
我把它降低到 1440,它起作用了。