怎么使用Python组合图像和文本
今天小编给大家分享一下怎么使用Python组合图像和文本的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
先决条件
1000x600 像素的图像。
一些演示图标 100x100 像素。
熟悉 Pipenv。
熟悉JupyterLab。
打开 安装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/.
我们将创建四个单元来处理这个迷你项目的四个部分:
加载图像。
创建目标图像并添加图标层。
创建文本层。
保存和显示目标图像。
在图像中加载
本节只是在 var 中加载图像base_img(假如你遵循笔记本在docs文件夹中的目录结构)。
from PIL import Image# Concatenating an imagebase_img = Image.open('../base_img.png')创建目标图像并添加图标层
我们根据基本图像的宽度和高度在此处创建目标图层,然后将该基本图像粘贴回。
然后我们使用 glob 库来获取我们图标的所有路径并将它们粘贴到基本图像的顶部。
# Add in icons using a globimport globfrom os.path import join, dirname, abspathdst_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 infont = ImageFont.truetype(os.path.join('fonts/OpenSans-Bold.ttf'), 58)import textwraptext = "Sample Text that is too long but let us write a bunch anyway"print(dst_img.width)max_text_width = 25wrapped_text = textwrap.wrap(text, width=max_text_width)# setup up a variable to invoke our text methoddraw = 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 inlinedisplay(Image.open('../dest_img.png'))以上就是"怎么使用Python组合图像和文本"这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注行业资讯频道。