欢迎访问宙启技术站
智能推送

PIL.Image库与图片文字添加的实用技巧分享

发布时间:2024-01-04 03:50:20

PIL.Image库是一个常用的Python图像处理库,它提供了丰富的图像处理功能,包括图像的加载、保存、裁剪、旋转、缩放等。

在使用PIL.Image库进行图像处理的过程中,有时我们需要向图像中添加文字,比如给图片添加标注、水印等。下面分享一些PIL.Image库与图片文字添加的实用技巧,带上使用例子来说明。

1. 添加文字水印

文字水印是一种常见的图片处理技巧,可以用来向图片中添加版权信息或作者信息。使用PIL.Image库可以轻松实现文字水印的添加。

from PIL import Image, ImageDraw, ImageFont

# 打开图片
image = Image.open('example.jpg')

# 创建一个可绘制的对象
draw = ImageDraw.Draw(image)

# 设置字体和字体大小
font = ImageFont.truetype('arial.ttf', size=30)

# 设置文字颜色
text_color = (255, 255, 255)

# 设置水印文字内容和位置
text = '? Your Name'
position = (image.size[0] - 200, image.size[1] - 50)

# 在图片上绘制文字
draw.text(position, text, font=font, fill=text_color)

# 保存图片
image.save('example_with_watermark.jpg')

在上述例子中,首先使用Image.open()方法打开一张图片,然后创建了一个可绘制的对象draw。接下来,通过ImageFont.truetype()方法指定字体和字体大小,再设置了水印文字的颜色。最后,使用draw.text()方法在图片上绘制了水印文字,并保存了处理后的图片。

2. 图片上添加标注

在科学研究、图像处理等领域,经常需要在图片上进行标注,如添加箭头、线段等。PIL.Image库提供了绘制线条和形状的绘图功能,可以用来实现这些标注需求。

from PIL import Image, ImageDraw

# 打开图片
image = Image.open('example.jpg')

# 创建一个可绘制的对象
draw = ImageDraw.Draw(image)

# 设置标注线的颜色和宽度
line_color = (255, 0, 0)
line_width = 3

# 绘制箭头
arrow_start = (100, 100)
arrow_end = (200, 200)
draw.line([arrow_start, arrow_end], fill=line_color, width=line_width)

arrow_head_length = 20
arrow_head_angle = 30
delta_x = arrow_head_length * math.cos(math.radians(arrow_head_angle))
delta_y = arrow_head_length * math.sin(math.radians(arrow_head_angle))
draw.line([arrow_end, (arrow_end[0] - delta_x, arrow_end[1] - delta_y)],
          fill=line_color, width=line_width)
draw.line([arrow_end, (arrow_end[0] - delta_x, arrow_end[1] + delta_y)],
          fill=line_color, width=line_width)

# 绘制线段
line_start = (300, 300)
line_end = (400, 400)
draw.line([line_start, line_end], fill=line_color, width=line_width)

# 保存图片
image.save('example_with_annotation.jpg')

在上述例子中,首先使用Image.open()方法打开一张图片,然后创建了一个可绘制的对象draw。接下来,设置了标注线的颜色和宽度。然后,使用draw.line()方法绘制了箭头和线段,并保存了处理后的图片。

总结:

在使用PIL.Image库进行图像处理时,经常会遇到需要向图片中添加文字的需求。通过使用PIL.Image库的ImageDrawImageFont等模块,我们可以轻松实现文字水印的添加以及图片标注的功能。以上只是一些简单的例子,实际应用中还可以根据需求进行进一步的扩展和优化。