如何将表情符号渲染为 Windows 下 Python 中的图像?
How to render emojis as images in Python under Windows?
我的目标是生成(在 Python 下的 Windows 中)位图图像渲染任何 unicode 字符,尤其包括表情符号。为了测试目的,我安装了几种表情符号友好的字体(包括 Symbola)。
到目前为止,我已经尝试过 PIL、matplotlib 和 pygame,但是其中 none 能够在 Windows 下完成(前两个显然可以在某些Linux / MacOS 版本,而 pygame 被明确限制为最多 0xffff 的字符,这排除了表情符号)。
我发现 reportlab 能够生成带有表情符号的 PDF(虽然它的位图渲染器无法正确渲染它们),但我仍然需要找到一种方法来从 PDF 中提取表情符号字符并将其转换为位图。我觉得必须有一个更简单的方法...
注意:这个问题与 Rendering Emoji with PIL 有关,但如果另一个库可以完成这项工作,我不一定要使用 PIL
我最终在 Is there any good python library for generating and rendering text in image format? 中找到了解决方案。尽管它基于第三方可执行文件,但如前所述,它很容易包装在 Python.
中
具体步骤如下:
- 从 https://www.imagemagick.org/script/download.php#windows
安装 ImageMagick
- 设置环境变量
MAGICK_HOME
到安装文件夹
- 安装 Pillow 以便能够在 Python (
conda install pillow
) 中轻松操作生成的图像
- 从 https://fontlibrary.org/en/font/symbola
下载并安装 Symbola 字体
还有我的测试脚本:
import os
import subprocess
import PIL.Image
to_render = ''
output_file = 'rendered_emoji.bmp'
subprocess.run([
os.path.join(os.environ['MAGICK_HOME'], 'magick.exe'),
'convert', '-font', 'Symbola', '-size', '50x50',
'-gravity', 'center', f'label:{to_render}', output_file])
image = PIL.Image.open(output_file)
image.show()
我的目标是生成(在 Python 下的 Windows 中)位图图像渲染任何 unicode 字符,尤其包括表情符号。为了测试目的,我安装了几种表情符号友好的字体(包括 Symbola)。
到目前为止,我已经尝试过 PIL、matplotlib 和 pygame,但是其中 none 能够在 Windows 下完成(前两个显然可以在某些Linux / MacOS 版本,而 pygame 被明确限制为最多 0xffff 的字符,这排除了表情符号)。
我发现 reportlab 能够生成带有表情符号的 PDF(虽然它的位图渲染器无法正确渲染它们),但我仍然需要找到一种方法来从 PDF 中提取表情符号字符并将其转换为位图。我觉得必须有一个更简单的方法...
注意:这个问题与 Rendering Emoji with PIL 有关,但如果另一个库可以完成这项工作,我不一定要使用 PIL
我最终在 Is there any good python library for generating and rendering text in image format? 中找到了解决方案。尽管它基于第三方可执行文件,但如前所述,它很容易包装在 Python.
中具体步骤如下:
- 从 https://www.imagemagick.org/script/download.php#windows 安装 ImageMagick
- 设置环境变量
MAGICK_HOME
到安装文件夹 - 安装 Pillow 以便能够在 Python (
conda install pillow
) 中轻松操作生成的图像
- 从 https://fontlibrary.org/en/font/symbola 下载并安装 Symbola 字体
还有我的测试脚本:
import os
import subprocess
import PIL.Image
to_render = ''
output_file = 'rendered_emoji.bmp'
subprocess.run([
os.path.join(os.environ['MAGICK_HOME'], 'magick.exe'),
'convert', '-font', 'Symbola', '-size', '50x50',
'-gravity', 'center', f'label:{to_render}', output_file])
image = PIL.Image.open(output_file)
image.show()