Eugene Kartashev
Eugene Kartashev

Reputation: 173

How to put stylized text on image in python?

I know that it's possible to put text on image in python with cv2 or pillow. But how to put stylized text? Like waved or colorful?

Upvotes: 0

Views: 1056

Answers (1)

jsbueno
jsbueno

Reputation: 110666

one have to use the other capabilities of whatever drawing library is in use to draw the text to stylize it. The way to go is to be creative by using simple variations, and then factoring out functions that could group all steps needed for a given effect.

I am not sure if there is a ready-made first class package that does that.

For example, the code bellow will simply paste text in different colors offsetting it a bit, using Pillow:

from PIL import Image, ImageFont, ImageDraw

img = Image.new("RGB", (530,140))
draw = ImageDraw.Draw(img)
fontpath = "/usr/share/calibre/fonts/liberation/LiberationSans-Bold.ttf"
font = ImageFont.truetype(fontpath, 60)
draw.text((42,42), "stack overflow!", fill=(0, 255, 255), font=font)
draw.text((40,40), "stack overflow!", fill=(255,0 , 0), font=font)
img.save("scratch/text01.png")

Offset text with varying colors

Or writing some code to to output one letter in each color, with a function that will go color by color - (you will learn that knowing the text size before rendering is very useful when working these effects)

...
from random import choice
colors = [(255, 128, 0), (0, 255, 128), (0, 255, 255), (255, 255, 0), (255, 255, 255), (255,0, 255)]

def colortext(pos, text, font, draw, colors):
    x, y = pos
    for letter in text:
        width = draw.textlength(letter, font)
        draw.text((x, y), letter, fill=choice(colors), font=font)
        x += width

colortext((40,40), text, font, draw, colors)

Upvotes: 1

Related Questions