alyssaeliyah
alyssaeliyah

Reputation: 2244

Python - Render a Slanted Font

This question is inline with the answer in my previous question in Stackoverflow.

I am creating a program that converts a text to image. I want to render it in using the font OCR A. But since OCR A font, has no corresponding font file for italics, I have to do the slanting of the upright font manually.

enter image description here

Upright Font

enter image description here

Slanted Font

Below is my initial code :

 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')

How do I manually slant the upright OCR A font? Thanks. You can download a sample ocra.ttf file here.

Upvotes: 1

Views: 487

Answers (1)

djangodude
djangodude

Reputation: 5680

This answer to a similar question is probably the easiest way, although it is not exactly what you want to do. Basically you render the upright font into an image then slant (shear) the entire image using PIL's Image.transform method.

To accomplish exactly what you are asking (slanting the font before imaging it) is possible, but would require a lot of work overriding PIL's truetype scheme to have the underlying font engine (FreeType) perform the slant transformation at the font level. PIL's truetype interface simply doesn't have a way to express a transform, so you'd have to override/patch it to pass that all the way down to FreeType where the font is set up.

Another option might be to skip PIL's truetype scheme and use a Python font-rendering library that allows you to set the font transform directly, then scrape the pixel data from that into your PIL Image. One such library is freetype-py.

Upvotes: 4

Related Questions