简体   繁体   中英

Can't center characters using Pillow and Python

I am trying to write characters in specific locations in an image. I am using Pillow v6, Python 3.6.

Here is my code, I draw char by char, passing the top left point that I calculated.

   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

The output is not centered, I got the character width and height from the font, then with my top left point I draw the rectangle enclosing the character. The character is not centered inside the rectangle.

Font: https://drive.google.com/open?id=1N9rN-AgjK83U9ZDycLKxjeMP3o36vbfg 在此处输入图片说明

I want it to be like this (another font) 另一种字体


EDIT Using Bidu Font editor I was able to remove the horizontal space (blue line). How can I center it vertically?. 在此处输入图片说明

Result so far ... 在此处输入图片说明

It looks like the font you are using contains non-centered numbers inside originally. So you should choose another font or you can modify your placechar.tff in a special editor for fonts.

Also you can calculate coordinate offsets for each symbol manually, store them into a dictionary and apply it for your text before drawing. It doesn't look like a good idea, but it would work also.

Calculate the width and height of the text to be drawn:

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')

结果

After taking the path that @Fomalhaut suggested, using font editor. I found Bidu font editor (link in the question). I was able to fix the horizontal space (also shown in the question). For vertical space, after searching the menus, I found setting option to change the ascent .

在此处输入图片说明

I decreased it to 1440, and it worked. 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM