二、文字轉成圖片,圖片上寫字

文字轉成圖片:

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

發佈了50 篇原創文章 · 獲贊 4 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章