使用 Python 组合图像和文本

打不倒的小乖兽 2021-08-25 12:02:40 浏览数 (1582)
反馈

这篇文章将使用 Pillow 图像库 以编程方式向图像添加文本和图标层。有兴趣的小伙伴们,可以一起来看看这篇文章。

先决条件

  1. 1000x600 像素的图像。
  2. 一些演示图标 100x100 像素。
  3. 熟悉 Pipenv。
  4. 熟悉JupyterLab
  5. 打开 安装fonts/OpenSans-Bold.ttf.

入门

让我们创建hello-img-layers目录并安装 Pillow。

# Make the `hello-img-layers` directory
$ mkdir hello-img-layers
$ cd hello-img-layers
# Create a folder to place your icons
$ mkdir icons

# Init the virtual environment
$ pipenv --three
$ pipenv install pillow
$ pipenv install --dev jupyterlab

在这个阶段,将你的 1000x600 图像添加到根目录 ( hello-img-layers) 作为base_img.png(至少这是我使用的)并将你的 100x100 图标添加到hello-img-layers/icons/.# Startup the notebook server

$ pipenv run jupyter-lab
# ... Server is now running on http://localhost:8888/lab

创建笔记本

http://localhost:8888/lab 上,选择从启动器创建一个新的 Python 3 笔记本。

确保此笔记本保存在hello-img-layers/docs/<your-file-name>.

我们将创建四个单元来处理这个迷你项目的四个部分:

  1. 加载图像。
  2. 创建目标图像并添加图标层。
  3. 创建文本层。
  4. 保存和显示目标图像。

在图像中加载

本节只是在 var 中加载图像base_img(假如你遵循笔记本在docs文件夹中的目录结构)。

from PIL import Image
# Concatenating an image
base_img = Image.open('../base_img.png')

创建目标图像并添加图标层

我们根据基本图像的宽度和高度在此处创建目标图层,然后将该基本图像粘贴回。

然后我们使用 glob 库来获取我们图标的所有路径并将它们粘贴到基本图像的顶部。

# Add in icons using a glob
import glob
from os.path import join, dirname, abspath

dst_img = Image.new('RGBA', (base_img.width, base_img.height))
dst_img.paste(base_img, (0, 0))

icons_dir = join(dirname(abspath("__file__")), '../icons')
icons = glob.glob(f"{icons_dir}/*")
for i, icon_path in enumerate(icons):
    icon = Image.open(icon_path)
    # @see https://stackoverflow.com/questions/5324647/how-to-merge-a-transparent-png-image-with-another-image-using-pil
    dst_img.paste(icon, (60 + (i * icon.width) + (i * 20), base_img.height - 100 - icon.height), icon)

创建文本层

该层将加载我们的Open Sans字体并将其绘制到图像上。

max_text_width=25我这里选择的是通过试验和错误。对于不同大小的图像,可能有一种更可重用的方法来处理此问题。

import os

# Add your own font in
font = ImageFont.truetype(os.path.join('fonts/OpenSans-Bold.ttf'), 58)

import textwrap
text = "Sample Text that is too long but let us write a bunch anyway"
print(dst_img.width)
max_text_width = 25
wrapped_text = textwrap.wrap(text, width=max_text_width)

# setup up a variable to invoke our text method
draw = ImageDraw.Draw(dst_img)

for i, line in enumerate(wrapped_text):
        # draw.text((0, height - (i * 20)), line, (0, 0, 0), font=font)
        draw.text((60, 100 + (i * 80)),line,(255,255,255),font=font)

保存和显示目标图像

最后,我们将保存并显示我们的基本图像。

dst_img.save('../dest_img.png')

# Display the image inline
display(Image.open('../dest_img.png'))

Outcome

总结

本篇文章为大家演示了如何使用该Pillow包以编程方式向图像添加文本和图标层,感谢大家的阅读。


0 人点赞