Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I draw text with different stroke and fill colors on images with python?

How can I draw text with different stroke and fill colors on images with python?

Here is some text with red stroke and gray fill.

Example

I tried to do this with PIL but there was no option for setting the stroke color.

like image 613
Seppo Erviälä Avatar asked Nov 08 '11 11:11

Seppo Erviälä


1 Answers

Using cairo (with much code taken from here):

import cairo

def text_extent(font, font_size, text, *args, **kwargs):
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)
    ctx = cairo.Context(surface)
    ctx.select_font_face(font, *args, **kwargs)
    ctx.set_font_size(font_size)
    return ctx.text_extents(text)

text='Example'
font="Sans"
font_size=55.0
font_args=[cairo.FONT_SLANT_NORMAL]
(x_bearing, y_bearing, text_width, text_height,
 x_advance, y_advance) = text_extent(font, font_size, text, *font_args)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(text_width), int(text_height))
ctx = cairo.Context(surface)
ctx.select_font_face(font, *font_args)
ctx.set_font_size(font_size)
ctx.move_to(-x_bearing, -y_bearing)
ctx.text_path(text)
ctx.set_source_rgb(0.47, 0.47, 0.47)
ctx.fill_preserve()
ctx.set_source_rgb(1, 0, 0)
ctx.set_line_width(1.5)
ctx.stroke()

surface.write_to_png("/tmp/out.png")

enter image description here

like image 89
unutbu Avatar answered Sep 20 '22 19:09

unutbu