你知道Python可以帮助向图像中添加文本吗?虽然Python不是图形编辑软件,但它能够很好地处理图像文件。在本文中,将在多个图像上放置一个示例文本“ExcelPerfect”。不用手动操作,也不用使用一些昂贵的软件,可以使用Python轻易达到同样的效果。这里需要使用PILLOW库(Python
Imaging Library),使用pip命令安装:- ImageDraw:用于创建新图像的类,我们将使用它向图片中添加文本。
img
= Image.open(r'D:\完美Excel\flower.jpg')如果使用的是Jupyter Notebook的话,可以使用内置函数display()在notebook中显示图片,如下图1所示。可以为添加到图片中的文字选择不同的字体。如果在Windows操作系统中,可以在Wondows搜索栏搜索“字体”,然后单击“字体设置”。在“字体设置”中,可以看到许多不同的字体,也能从网上下载新字体供后面使用。这里想使用字体“Gill Sans”,能够从设置中找到该字体文件的位置,如下图2所示。有了这个字体文件,现在可以创建一个字体对象,在Python中的图像上部绘制。在下面的代码行中:font
= ImageFont.truetype(r'C:\WINDOWS\FONTS\GILSANUB.TTF',30)现在需要创建一个ImageDraw对象来修改该图像。下面的draw.text()接受以下参数:3.fill–文本的RGB颜色值(255表示白色,0表示黑色)draw
= ImageDraw.Draw(img)draw.text((10,10),'ExcelPerfect',
font = font, fill = (255, 255, 255))注意,ImageDraw对象实际上修改了Image对象。为了显示更新后的图像,可以再次使用display(img):1.确定文本的大小,这应该动态设置,因为每个图像的大小不同。2.此外,动态确定文本的起始(x,y)坐标。由于图像大小不同,坐标会有所不同。可以通过调用size属性来获得图像(即画布)的大小。在本例中,我们的图像宽869像素,高633像素。我们将设置文本大小,使整个文本行大约占图像宽度的1/3。ImageFont对象的默认字体大小为10。要获取文本尺寸(宽度和高度)并计算比例因子,执行以下操作:text_width,
text_height =
ImageFont.truetype(r'C:\WINDOWS\FONTS\GILSANUB.TTF').getsize(text)img
= Image.open(r'D:\完美Excel\flower.jpg')img_width,
img_height = img.sizescaler
= img_width/3/text_width在这个例子中,scaler大约是3.5,这意味着我们的字体大小将是10*3.5=35。文本宽度和高度也将相应缩放。scale_text_font
= int(default_font_size * scaler)scale_text_width
= int(scaler * text_width)scale_text_height
= int(scaler * text_height)font
= ImageFont.truetype(r'C:\WINDOWS\FONTS\GILSANUB.TTF', size = scale_text_font)draw
= ImageDraw.Draw(img)start_x
= img_width - scale_text_width - 20start_y
= img_height - scale_text_height - 20draw.text((start_x,
start_y), text = text, font = font, fill = (255,255,255))img.save(r'D:\完美Excel\flower_w_text.jpg')要向多个图像添加文本,让我们将所有图像放在同一个文件夹中。然后可以使用os.listdir()从该文件夹中获取所有文件名,并处理每个文件。完整代码如下:text_width,
text_height =
ImageFont.truetype(r'C:\WINDOWS\FONTS\GILSANUB.TTF').getsize(text)folder_path
= r'D:\完美Excel\images'for
f in os.listdir(folder_path):img = Image.open(rf'{folder_path}\{f}')img_width, img_height = img.sizescaler = img_width/2/text_widthscale_text_font = int(default_font_size *
scaler)scale_text_width = int(scaler * text_width)scale_text_height = int(scaler *
text_height)font =
ImageFont.truetype(r'C:\WINDOWS\FONTS\GILSANUB.TTF', size = scale_text_font)draw = ImageDraw.Draw(img)start_x = img_width - scale_text_width - 20start_y = img_height - scale_text_height -
20draw.text((start_x, start_y), text = text,
font = font, fill = (0,0,0))file_name = f.split('.')[0] + '_w_text.jpg'img.save(rf'{folder_path}\{file_name}')注:本文学习整理自pythoninoffice.com,供有兴趣的朋友学习参考。
|