此问题与我在Stackoverflow中的previous question中的答案一致。
我正在创建一个将文本转换为图像的程序。我想使用字体OCR A
进行渲染。但是由于OCR A
字体没有对应的斜体字体文件,因此我必须手动进行直立字体的倾斜。
直立字体
倾斜字体
下面是我的初始代码:
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import numpy as np
#Returns the text size in terms of width and height.
def getSize(txt, font):
testImg = Image.new('RGB', (1, 1))
testDraw = ImageDraw.Draw(testImg)
return testDraw.textsize(txt, font)
text = 'CNN Font Recognition Model'
font_size = 12
font = ImageFont.truetype('ocra.ttf' , font_size)
#ocra.ttf is a font file for OCR A Regular font (I have to render it slanted)
width, height = getSize(text, font)
#Creates an image with white background of constant size.
img = Image.new('RGB',(width, height), 'white')
d = ImageDraw.Draw(img)
d.text((0,0), text, fill='black', font=font)
img.save('slanted_ocr_a.png')
如何手动倾斜直立的OCR A字体?谢谢。您可以下载样本ocra.ttf
文件here.
This answer到类似的问题可能是最简单的方法,尽管这并不是您想要的。基本上,您将直立字体呈现为图像,然后使用PIL的Image.transform
方法倾斜(剪切)整个图像。
要精确地完成您所要的内容(使字体之前成像),但是要使PIL的truetype
方案具有基础字体引擎(FreeType)perform the slant transformation at the font level,需要大量工作。 PIL的truetype
接口根本没有表达转换的方法,因此您必须重写/修补它才能将其一直传递到设置字体的FreeType。