可以使用如下函数对图片加文字:
from PIL import Image,ImageDraw,ImageFont
def make_img():
font = ImageFont.truetype('simsun.ttc',24)
img = Image.new('RGB',(300,200),(255,255,255))
draw = ImageDraw.Draw(img)
draw.text((0,60),'你好',(0,0,0),font=font)
img.save('d:/a.png', 'png')
但是如果想让文字居中,就要计算字符的宽度,然后设置偏移量,在网上搜索得到如下方法:
def get_width( c ):
"""Return the screen column width for unicode ordinal o."""
widths = [ (126, 1), (159, 0), (687, 1), (710, 0), (711, 1), (727, 0), (733, 1), (879, 0), (1154, 1), (1161, 0), (4347, 1), (4447, 2), (7467, 1), (7521, 0), (8369, 1), (8426, 0), (9000, 1), (9002, 2), (11021, 1), (12350, 2), (12351, 1), (12438, 2), (12442, 0), (19893, 2), (19967, 1),
(55203, 2), (63743, 1), (64106, 2), (65039, 1), (65059, 0), (65131, 2), (65279, 1), (65376, 2), (65500, 1), (65510, 2), (120831, 1), (262141, 2), (1114109, 1), ]
o = ord(c)
if o == 0xe or o == 0xf:
return 0
for num, wid in widths:
if o <= num:
return wid
return 1
def get_str_width(string):
width = 0
for c in string:
width += get_width(c)
return width
这个方法根据unicode的官方EastAsianWidth文档整理出字符宽度的范围表,然后使用unicode代码查表。
得出函数如下:
def make_img():
img_height = 200
img_width = 300
font_size = 24
font_width=0
s1 = '啊啊啊啊啊啊啊啊啊啊'
s2 = 'abcdefghigklmnopqrst'
s3 = '01234567890123456789'
font = ImageFont.truetype('msyh.ttc',font_size)
img = Image.new('RGB',(img_width,img_height),(255,255,255))
draw = ImageDraw.Draw(img)
draw.text(((img_width - get_str_width(s1)*font_size/2)/2,60),s1,(0,0,0),font=font)
draw.text(((img_width - get_str_width(s2)*font_size/2)/2,100),s2,(0,0,0),font=font)
draw.text(((img_width - get_str_width(s3)*font_size/2)/2,140),s3,(0,0,0),font=font)
img.save('d:/a.png', 'png')
结果如下图:
与预期不一样啊,应该是不能用fontsize简单的去计算每一个字符的宽度,就像i和m,即使都是font_size=24,他们的字符所占用的像素数还是不一样的,暂时还没找到解决方案。