是否有一个命令行工具可以将TTF文件中的字形转换为PNG(或其他位图图像格式)?
如果没有现成的命令行工具,你会如何使用C++、Perl、Python或Ruby中的一个从Ubuntu box轻易获取的语言来完成这个任务?
是否有一个命令行工具可以将TTF文件中的字形转换为PNG(或其他位图图像格式)?
如果没有现成的命令行工具,你会如何使用C++、Perl、Python或Ruby中的一个从Ubuntu box轻易获取的语言来完成这个任务?
可能是与如何在Mac上免费将TTF字形转换为.png文件?部分重复。
Imagemagick可以满足此类需求,应该可以在Mac/Linux/Windows上正常工作。 :-)
convert -background none -fill black -font font.ttf -pointsize 300 label:"Z" z.png
如果需要进行批量转换,也许可以考虑使用一个名为ttf2png的小型Ruby脚本。
由于还没有人真正解决了涉及C++、Python、Ruby或Perl的部分,这里介绍一下Python3的方式。我已经尽可能地进行了描述,但您可以简化它以使其按照您需要的方式工作。
PIL 的 ImageDraw 和 ImageFont 模块。
# pip install Pillow
from PIL import Image, ImageFont, ImageDraw
# use a truetype font (.ttf)
# font file from fonts.google.com (https://fonts.google.com/specimen/Courier+Prime?query=courier)
font_path = "fonts/Courier Prime/"
font_name = "CourierPrime-Regular.ttf"
out_path = font_path
font_size = 16 # px
font_color = "#000000" # HEX Black
# Create Font using PIL
font = ImageFont.truetype(font_path+font_name, font_size)
# Copy Desired Characters from Google Fonts Page and Paste into variable
desired_characters = "ABCČĆDĐEFGHIJKLMNOPQRSŠTUVWXYZŽabcčćdđefghijklmnopqrsštuvwxyzž1234567890‘?’“!”(%)[#]{@}/&\<-+÷×=>®©$€£¥¢:;,.*"
# Loop through the characters needed and save to desired location
for character in desired_characters:
# Get text size of character
width, height = font.getsize(character)
# Create PNG Image with that size
img = Image.new("RGBA", (width, height))
draw = ImageDraw.Draw(img)
# Draw the character
draw.text((-2, 0), str(character), font=font, fill=font_color)
# Save the character as png
try:
img.save(out_path + str(ord(character)) + ".png")
except:
print(f"[-] Couldn't Save:\t{character}")
convert -background none -font my-icons-font.ttf -fill black -size "240x240" label:"0" +repage -depth 8 icon0@1x.png
其中“0”是我所有图标映射的字符。额外的选项允许我正确生成所有字符(图标),因为有些图标会被常规命令裁剪(+repage -depth完成了这项工作)。
为了我的目的,我创建了一个shell脚本。如果已安装ImageMagick,则在macOS上运行良好。其他平台未确定。
#!/bin/bash
FONT_NAME="$1"
FONT_SIZE="$2"
FILE_NAME=$(basename ${FONT_NAME} .ttf)"-${FONT_SIZE}.png"
read -r -d '' CHARSET << EOM
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789.:,;(*!?}^)#\${\%
&-+@'\"[]<>
EOM
convert -font ${FONT_NAME} -pointsize ${FONT_SIZE} label:"${CHARSET}" "${FILE_NAME}"
> sh ttf2png.sh alagard.ttf 20
然后,该脚本将生成一个名为alagard-20.png
的文件。wget http://sid.ethz.ch/debian/ttf2png/ttf2png-0.3.tar.gz
tar xvzf ttf2png-0.3.tar.gz
cd ttf2png-0.3 && make
./ttf2png ttf2png -l 11 -s 18 -e -o test.png /path/to/your/font.ttf
eog test.png&