Python - Make Text Slanted with PIL Library

怎甘沉沦 提交于 2020-02-24 20:58:19

问题


I'd like to control the slantiness (italic) of a text according a given degree and direction (left or right tilt) similar as presented in the image below:

I have stumble upon this great answer: How does perspective transformation work in PIL?, played with the code, and read the documentation of AFFINE but it's still isn't clear enough for me.

Can someone please explain me (mathematic and logic wise), how can I do this? Thank you.


回答1:


To generate some text we can use any method, here I am using ImageFont to get a black and white mask.

def generate_text(text):
    fnt = ImageFont.truetype('arial.ttf', 72)
    img = Image.new('1', fnt.getsize(text))
    mask = [x for x in fnt.getmask(text, mode='1')]
    img.putdata(mask)
    img = img.convert('RGB')
    return img

Then, I would like to add padding on the left and right because we will be shearing the text horizontally.

def add_border(img, width):
    new = Image.new('RGB', (img.width + 2 * width, img.height), (0, 0, 0))
    new.paste(img, (width, 0))
    return new

Finally, I will use an affine transformation using the b value, which if you look a the formula, it is the coefficient of y that will be added to x. So, a larger b will shear horizontally more. In this case I am using 2.

def shear(img, shear):
    shear = img.transform(img.size, Image.AFFINE, (1, shear, 0, 0, 1, 0))
    return shear

The calling code:

img = generate_text('test')
img = add_border(img, 200)
img = shear(img, 2)


来源:https://stackoverflow.com/questions/51694433/python-make-text-slanted-with-pil-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!