【转载】PIL imagefont ImageDraw.text 文字加边框

使用pil给图片中的文字加个边框,像这样

from PIL import Image,ImageDraw,ImageFont
import os
 
 
# 用于文字边框展示,传入draw,坐标x,y,字体,边框颜色和填充颜色
def text_border(draw, x, y, font, shadowcolor, fillcolor):
    # thin border
    draw.text((x - 1, y), text, font=font, fill=shadowcolor)
    draw.text((x + 1, y), text, font=font, fill=shadowcolor)
    draw.text((x, y - 1), text, font=font, fill=shadowcolor)
    draw.text((x, y + 1), text, font=font, fill=shadowcolor)
 
    # thicker border
    draw.text((x - 1, y - 1), text, font=font, fill=shadowcolor)
    draw.text((x + 1, y - 1), text, font=font, fill=shadowcolor)
    draw.text((x - 1, y + 1), text, font=font, fill=shadowcolor)
    draw.text((x + 1, y + 1), text, font=font, fill=shadowcolor)
 
    # now draw the text over it
    draw.text((x, y), text, font=font, fill=fillcolor)
 
 
 
x, y = 10, 10
 
fname1 = "frameinstance0.png"
im = Image.open(fname1)
pointsize = 30
fillcolor = (0,0,0)
shadowcolor = "yellow"
 
text = "hi there"
 
font="impact.ttf"
draw = ImageDraw.Draw(im)
font = ImageFont.truetype(font, pointsize)
 
# 调用函数
text_border(draw,x,y,font,shadowcolor,fillcolor)
 
fname2 = "c:/test2.jpg"
im.show()
im.save(fname2)