二、文字转成图片,图片上写字

文字转成图片:

from PIL import Image,ImageDraw,ImageFont
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")

图片上添加文字:

from PIL import Image,ImageDraw,ImageFont
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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值