Python PIL | ImageDraw.Draw.text()
PIL 是Python图像库,它为Python解释器提供图像编辑功能。 ImageDraw
模块为 Image 对象提供简单的 2D 图形。您可以使用此模块创建新图像、注释或修饰现有图像,以及动态生成图形以供 Web 使用。
ImageDraw.Draw.text()
在给定位置绘制字符串。
Syntax:
ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”)
Parameters:
xy – Top left corner of the text.
text – Text to be drawn. If it contains any newline characters, the text is passed on to multiline_text()
fill – Color to use for the text.
font – An ImageFont instance.
spacing – If the text is passed on to multiline_text(), the number of pixels between lines.
align – If the text is passed on to multiline_text(), “left”, “center” or “right”.
Return Type:
returns an image with text.
使用的图像:
代码:使用 PIL | ImageDraw.Draw.text()
# Importing Image and ImageFont, ImageDraw module from PIL package
from PIL import Image, ImageFont, ImageDraw
# creating a image object
image = Image.open(r'C:\Users\System-Pc\Desktop\rose.jpg')
draw = ImageDraw.Draw(image)
# specified font size
font = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 20)
text = 'LAUGHING IS THE \n BEST MEDICINE'
# drawing text size
draw.text((5, 5), text, font = font, align ="left")
image.show()
输出:
另一个例子:这里我们改变参数。
使用的图像:
代码:使用 PIL | ImageDraw.Draw.text()
# Importing Image and ImageFont, ImageDraw module from PIL package
from PIL import Image, ImageFont, ImageDraw
# creating a image object
image = Image.open(r'C:\Users\System-Pc\Desktop\flower.jpg')
draw = ImageDraw.Draw(image)
# specified font size
font = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf', 20)
text = 'LAUGHING IS THE \n BEST MEDICINE'
# drawing text size
draw.text((5, 5), text, fill ="red", font = font, align ="right")
image.show()
输出: