Is there a way to outline text with a dark line in PIL?

后端 未结 5 1482
轮回少年
轮回少年 2020-12-17 15:04

I\'m using python/PIL to write text on a set of PNG images. I was able to get the font I wanted, but I\'d like to now outline the text in black.

5条回答
  •  醉梦人生
    2020-12-17 15:13

    This is how I handled the problem when I needed to do it for frame counters. Just a heads up if you start to push this too far for the thickness, then you will need more draws to cover your areas you're missing.

    from PIL import Image,ImageDraw,ImageFont
    import os
    
    #setting varibles
    imgFile = "frame_0.jpg"
    output = "frame_edit_0.jpg"
    font = ImageFont.truetype("arial.ttf", 30)
    text = "SEQ_00100_SHOT_0004_FR_0001"
    textColor = 'white'
    shadowColor = 'black'
    outlineAmount = 3
    
    #open image
    img = Image.open(imgFile)
    draw = ImageDraw.Draw(img)
    
    #get the size of the image
    imgWidth,imgHeight = img.size
    
    #get text size
    txtWidth, txtHeight = draw.textsize(text, font=font)
    
    #get location to place text
    x = imgWidth - txtWidth - 100
    y = imgHeight - txtHeight - 100
    
    #create outline text
    for adj in range(outlineAmount):
        #move right
        draw.text((x-adj, y), text, font=font, fill=shadowColor)
        #move left
        draw.text((x+adj, y), text, font=font, fill=shadowColor)
        #move up
        draw.text((x, y+adj), text, font=font, fill=shadowColor)
        #move down
        draw.text((x, y-adj), text, font=font, fill=shadowColor)
        #diagnal left up
        draw.text((x-adj, y+adj), text, font=font, fill=shadowColor)
        #diagnal right up
        draw.text((x+adj, y+adj), text, font=font, fill=shadowColor)
        #diagnal left down
        draw.text((x-adj, y-adj), text, font=font, fill=shadowColor)
        #diagnal right down
        draw.text((x+adj, y-adj), text, font=font, fill=shadowColor)
    
    #create normal text on image
    draw.text((x,y), text, font=font, fill=textColor)
    
    img.save(output)
    print 'Finished'
    os.startfile(output)
    

提交回复
热议问题