from PIL import Image, ImageFont, ImageDraw
img = Image.open("D:\\cygwin\\home\\Administrator\\test.png")
draw = ImageDraw.Draw(img)
myFont = ImageFont.truetype("C:\\WINDOWS\\Fonts\\Arial.ttf",size=40)
fillcolor = "#ff0000"
width, height = img.size
draw.text((width-40,0), "99", font=myFont, fill=fillcolor)
img.save("result.jpg","jpeg")
img.show()
这是第一个版本。
下面是第二个版本。
from PIL import Image, ImageFont, ImageDraw
def add_num(img):
draw = ImageDraw.Draw(img)#首先创建Draw类的实例
myFont = ImageFont.truetype("C:\\WINDOWS\\Fonts\\Arial.ttf",size=40)#PIL库支持truetype和opentype两种字体,这里用的是truetype字体。myFont规定了字符格式。
fillcolor = "#ff0000"
width, height = img.size
draw.text((width-60,10), "30", font=myFont, fill=fillcolor)#参数(width,height)指定的是字符离图片边缘的距离。
img.save("result.jpg","jpeg")
return 0
if __name__=="__main__":
img = Image.open("D:\\cygwin\\home\\Administrator\\test.png")
add_num(img)
这是一个很简单的小项目。
往图片上添加字符,需要解决字符与添加两个问题。ImageFont用来解决字符问题,ImageDraw的text()方法能够把字符添加上去。这是解决该问题的核心。 想要了解细节的可以去看官方文档。
本文介绍了一个简单的Python项目,演示如何使用PIL库在图片上添加文字。通过ImageFont设置字体样式,利用ImageDraw的text方法将指定的文字添加到图片指定位置。

2263

被折叠的 条评论
为什么被折叠?



