Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text Shadow With Python

I have added some text over an image using PIL

I'd like to add a text shadow, with a certain shadow radius and shadow opacity.

I've been able to fake this a bit (it doesn't work too well) by drawing a shadow, before I draw some text, and place it a little bit above the text.

    draw.text((x, y + 2), text, font = some_font, fill = (208,208,208)) #shadow
    draw.text((x, y), text, font = some_font, fill = (255,255,255)) #text

However, such an approach does not allow for shadow-radius, opacity css-style properties.

Is there a better way to create a text shadow with Python? If so, how?

like image 495
GangstaGraham Avatar asked Jan 12 '23 07:01

GangstaGraham


2 Answers

Have a look at these examples.

Example 1

Example 2

and the last one is kinda similar to what you attempted.

import Image, ImageFont, ImageDraw

import win32api, os

x, y = 10, 10

fname1 = "c:/test.jpg"
im = Image.open(fname1)
pointsize = 30
fillcolor = "red"
shadowcolor = "yellow"

text = "hi there"

font = win32api.GetWindowsDirectory() + "\\Fonts\\ARIALBD.TTF"
draw = ImageDraw.Draw(im)
font = ImageFont.truetype(font, pointsize)

# thin border
draw.text((x-1, y), text, font=font, fill=shadowcolor)
draw.text((x+1, y), text, font=font, fill=shadowcolor)
draw.text((x, y-1), text, font=font, fill=shadowcolor)
draw.text((x, y+1), text, font=font, fill=shadowcolor)

# thicker border
draw.text((x-1, y-1), text, font=font, fill=shadowcolor)
draw.text((x+1, y-1), text, font=font, fill=shadowcolor)
draw.text((x-1, y+1), text, font=font, fill=shadowcolor)
draw.text((x+1, y+1), text, font=font, fill=shadowcolor)

# now draw the text over it
draw.text((x, y), text, font=font, fill=fillcolor)

fname2 = "c:/test2.jpg"
im.save(fname2)

os.startfile(fname2)
like image 150
cyberbemon Avatar answered Jan 17 '23 10:01

cyberbemon


Your best bet is something along the lines of:

  1. create a new image/layer in RGBA format with the initial alpha set to fully transparent,
  2. add your text to it as is with the text alpha set to full opaque,
  3. take a copy of the text layer,
  4. shift it by your shadow direction,
  5. scale it by your shadow scale factor,
  6. replace the colour of your text with a shadow colour that has an alpha for the shadow density.
  7. then merge/paste the shadow on to the original image
  8. followed by merging/paste on the text layer.
like image 42
Steve Barnes Avatar answered Jan 17 '23 11:01

Steve Barnes