文字转成图片:
def text2Image(self):
text = u"这是一段测试文本,test 123。"
im = Image.new("RGB", (300, 50), (255, 255, 255))
dr = ImageDraw.Draw(im)
font = ImageFont.truetype(os.path.join("fonts", "msyh.ttf"), 14)
dr.text((10, 5), text, font=font, fill="#000000")
im.show()
im.save("t.png")
图片上添加文字:
def addText2Image(self):
# get an image
base = Image.open('image2.png').convert('RGBA')
# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255, 255, 255, 0))
# get a drawing context
d = ImageDraw.Draw(txt)
fnt = ImageFont.truetype(font='FreeMono.ttf', size=40)
# draw text, half opacity
d.text((10, 10), "Hello", font=fnt, fill=ImageColor.colormap['red'])
# draw text, full opacity
d.text((10, 60), "World", font=fnt, fill=ImageColor.colormap['salmon'])
out = Image.alpha_composite(base, txt)
out.show()
效果如下:
参考文章:
Example: Draw Partial Opacity Text http://pillow.readthedocs.io/en/4.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text