User Tools

Site Tools


doc:appunti:prog:pythonmagick_text_shadow_outline

Drawing Text with Shadow Outline using Python Imagemagick

Here it is a small recipe to create a shadow outline effect around a text label, using the ImageMagick library in Python. You need to install the Imagemagick Python library, e.g. the python3-pythonmagick package if you are using a Debian GNU/Linux distro.

The result can be used to overlay a label over an image, in a subtitle-like effect.

Text Shadow Outline in Python

The Source Code

#!/usr/bin/python3
 
import PythonMagick as pm
 
__author__ = "Niccolo Rigacci"
__copyright__ = "Copyright 2020 Niccolo Rigacci <niccolo@rigacci.org>"
__license__ = "GPLv3-or-later"
__email__ = "niccolo@rigacci.org"
__version__ = "0.1.0"
 
label = """Text with Shadow Outline Effect
Using Imagemagick Python (PythonMagick)
To Create Subtitles-like Labels"""
 
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# Image size.
img_width = 800
img_heigth = 600
 
# Avaliable fonts: Arial, Helvetica, Courier, Verdana, ...
# See full list with: convert -list font
font_name = 'Arial'
 
# Color. String constant or (R, G, B, A) 16bit values.
#shadow_color = 'black'
#fill_color = 'white'
shadow_color = pm.Color(0, 0, 0, 0)
fill_color = pm.Color(65535, 65535, 65535, 0)
 
# Font size in pixels.
font_size = img_heigth * 0.045
# Stroke width in pixels.
stroke_width = font_size * 0.25
 
# Align text to bottom center.
text_gravity = pm.GravityType.SouthGravity
bottom_margin = font_size
 
#-------------------------------------------------------------------------
im = pm.Image('%dx%d' % (img_width, img_heigth), 'transparent')
im.font(font_name)
im.fontPointsize(font_size)
#im.antiAlias(True)
#im.strokeAntiAlias(True)
 
im.fillColor(shadow_color)
im.strokeColor(shadow_color)
im.strokeWidth(stroke_width)
im.annotate(label, '+0+%d' % (bottom_margin,), text_gravity)
im.blur(stroke_width, stroke_width / 2.0)
 
im.fillColor(fill_color)
im.strokeColor(fill_color)
im.strokeWidth(0)
im.annotate(label, '+0+%d' % (bottom_margin,), text_gravity)
 
im.write('pythonmagick-shadow-outline.png')
doc/appunti/prog/pythonmagick_text_shadow_outline.txt · Last modified: 2020/03/27 09:14 by niccolo