本文共 1165 字,大约阅读时间需要 3 分钟。
文字转成图片:
from PIL import Image,ImageDraw,ImageFontdef 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")
图片上添加文字:
from PIL import Image,ImageDraw,ImageFontdef 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://ziivi.baihongyu.com/