簡體   English   中英

如何在 PIL 中添加文本邊框?

[英]How to add a border of text in PIL?

from PIL import ImageFont,Image, ImageDraw
imagefile = "base.jpg"
im1 = Image.open(imagefile)
draw = ImageDraw.Draw(im1)
draw.text((100,100),"helloworld")
im1.save("res.png")

我想在“hello world”中添加一個矩形邊框,就像這樣,

在此處輸入圖像描述

在此處輸入圖像描述

要在文本周圍繪制一個矩形,您需要知道文本的高度和寬度。 因此解決方案應該是:

from PIL import ImageFont,Image, ImageDraw
imagefile = "base.jpg"
im1 = Image.open(imagefile)
draw = ImageDraw.Draw(im1)
font = ImageFont.load_default()
text = "helloworld"
draw.text((100,100),text, font=font)
text_width, text_height = font.getmask(text).size
draw.rectangle(((100, 100), (100 + text_width, 100 + text_height)), outline=(0,0,255))
im1.save("res.png")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM