如何在图像上旋转打印为文本的表情符号?

2024-10-01 00:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我现在正在做的:

from PIL import Image, ImageDraw, ImageFont, ImageFilter

fnt = ImageFont.truetype(font="NotoColorEmoji.ttf", size=109, layout_engine=ImageFont.LAYOUT_RAQM)
im = Image.open('1.png')
im = im.filter(ImageFilter.GaussianBlur(100))
draw = ImageDraw.Draw(im)
draw.text((66, 232), "😀" ,fill="#faa", embedded_color=True, font=fnt)
im.show()

Tags: fromimageimportsizepilttffontdraw
1条回答
网友
1楼 · 发布于 2024-10-01 00:31:02

你需要

  1. 确定呈现表情符号的大小w.r.t.设置字体
  2. 导出旋转中心w.r.t.渲染文本的位置和确定的大小
  3. 在与输入图像大小相同的透明图像上打印文本
  4. 以所需角度和导出的旋转中心旋转该图像,然后
  5. 将该文本图像粘贴到实际输入图像上

以下是包含一些可视化开销的代码:

from PIL import Image, ImageDraw, ImageFont

# Load image
im = Image.open('path/to/your/image.png')

# Set up font, text, location, and rotation angle
fnt = ImageFont.truetype(font="NotoColorEmoji.ttf", size=109,
                         layout_engine=ImageFont.LAYOUT_RAQM)
txt = '😀'
loc = (50, 50)
ang = 123.45

# Get dimensions of rendered text using the specified font
fnt_dim = fnt.getsize(txt)

# Calculate rotation center, i.e. the center of the emoji, w.r.t. the
# text's location
rot_cnt = (loc[0] + fnt_dim[0] // 2, loc[1] + fnt_dim[1] // 2)

# Generate transparent image of the same size as the input, and print
# the text there
im_txt = Image.new('RGBA', im.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(im_txt)
draw.text(loc, txt, fill="#faa", embedded_color=True, font=fnt)

# Rotate text image w.r.t. the calculated rotation center
im_txt = im_txt.rotate(ang, center=rot_cnt)

# Paste text image onto actual image
im.paste(im_txt, mask=im_txt)

# Just for comparison: Print text upright directly on input image
im2 = im.copy()
draw = ImageDraw.Draw(im2)
draw.text(loc, txt, fill="#faa", embedded_color=True, font=fnt)

# Just for visualization
import matplotlib.pyplot as plt

plt.figure(figsize=(18, 6))
plt.subplot(1, 3, 1), plt.imshow(im)
plt.subplot(1, 3, 2), plt.imshow(im2)
plt.subplot(1, 3, 3), plt.imshow(Image.blend(im, im2, 0.5))
plt.tight_layout(), plt.show()

这就是输出:

Output

从两个版本的混合图像来看,旋转表情符号的位置非常完美。有些失真是由于表情符号的非方形大小造成的

                    
System information
                    
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.2
Matplotlib:    3.4.2
Pillow:        8.2.0
                    

相关问题 更多 >