Python PIL-在图片前添加文字(图片上方,图片上方)

时间:2019-11-11 17:43:00

标签: python text python-imaging-library

如何在图片上方添​​加文字(即不在图片内)?

see example

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 

img = Image.open("SAMPLE-IN.png")
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("FONTS/arial.ttf", 36)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0,0),"Sample Text",(0,255,255),font=font)
img.save('sample-out.jpg')

1 个答案:

答案 0 :(得分:1)

您应该创建一个比原始图像大的图像,将第一个图像和文本粘贴到该图像上,如下所示:

from PIL import Image, ImageFont, ImageDraw, ImageOps
img = Image.open("SAMPLE-IN.png")
img = ImageOps.expand(img, border=10, fill=(255,255,255))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("FONTS/arial.ttf", 36)
draw.text((0,0),"Sample Text",(0,255,255),font=font)
img.save('sample-out.jpg')