[英]Can't center characters using Pillow and Python
我正在嘗試在圖像的特定位置寫入字符。 我正在使用Pillow v6,Python 3.6。
這是我的代碼,我按字符繪制char,並傳遞我計算出的左上角。
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字體編輯器,我可以刪除水平空間(藍線)。 如何垂直居中?
看起來您正在使用的字體最初包含非中心數字。 因此,您應該選擇其他字體,或者可以在特殊的字體編輯器中修改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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.