Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

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

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.

This is what I have: as you can see, if the background is white it is difficult to read.

enter image description here

This is the goal:

enter image description here

Is there a way to accomplish this with PIL? If not, I am open to hearing other suggestions, but no promises because I've already begun a large project in python using PIL.

The section of code that deals with drawing on the images:

for i in range(0,max_frame_int + 1):
    writeimg = Image.open("frameinstance" + str(i) + ".png")
    newimg = Image.new("RGB", writeimg.size)
    newimg.paste(writeimg)
    width_image = newimg.size[0]
    height_image = newimg.size[1]
    draw = ImageDraw.Draw(newimg)
    # font = ImageFont.truetype(<font-file>, <font-size>)
    for font_size in range(50, 0, -1):
        font = ImageFont.truetype("impact.ttf", font_size)
        if font.getsize(meme_text)[0] <= width_image:
            break
    else:
        print('no fonts fit!')

    # draw.text((x, y),"Sample Text",(r,g,b))
    draw.text((int(0.05*width_image), int(0.7*height_image)),meme_text,(255,255,255),font=font)
    newimg.save("newimg" + str(i) +".png")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can take a look at this Text Outline Using PIL:

import Image, ImageFont, ImageDraw

import win32api, os

x, y = 10, 10

fname1 = "c:/test.jpg"
im = Image.open(fname1)
pointsize = 30
fillcolor = "red"
shadowcolor = "yellow"

text = "hi there"

font = win32api.GetWindowsDirectory() + "\Fonts\ARIALBD.TTF"
draw = ImageDraw.Draw(im)
font = ImageFont.truetype(font, pointsize)

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

fname2 = "c:/test2.jpg"
im.save(fname2)

os.startfile(fname2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...