使用 PIL 在图片上叠加文字 [英] Overlay text on a picture with PIL

查看:90
本文介绍了使用 PIL 在图片上叠加文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在图片上写一些文字(可能有一些简单的效果,比如阴影).我怎样才能用 PIL 做到这一点?

I just wanted to write some text on picture (possibly with some simple effects like shadow). How can I do this with PIL?

推荐答案

首先安装Python Imaging Library (pip install Pillow)

First install Python Imaging Library (pip install Pillow)

注意:您可能需要更改字体文件font_fname 的路径.

Note: you may need to change the path to your font file font_fname.

import numpy as np
import PIL
import PIL.Image as Image
import PIL.ImageDraw as ImageDraw
import PIL.ImageFont as ImageFont

font_fname = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'
font_size = 200
font = ImageFont.truetype(font_fname, font_size)

h, w = 1080, 1920
bg_colour = (255, 255, 255)
bg_image = np.dot(np.ones((h,w,3), dtype='uint8'), np.diag(np.asarray((bg_colour), dtype='uint8')))
image0 = Image.fromarray(bg_image)
draw = ImageDraw.Draw(image0)
draw.text((530, 160), "hello world", font=font, fill='rgb(0, 0, 0)')
image0.save('hello_world.jpg')

这篇关于使用 PIL 在图片上叠加文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆