MCPcopy Create free account
hub / github.com/ActiveState/code / dropShadow

Function dropShadow

recipes/Python/474116_Drop_shadows_with_PIL/recipe-474116.py:9–49  ·  view source on GitHub ↗

Add a gaussian blur drop shadow to an image. image - The image to overlay on top of the shadow. offset - Offset of the shadow from the image as an (x,y) tuple. Can be positive or negative. background - Background colour behind the image. shadow - Sha

( image, offset=(5,5), background=0xffffff, shadow=0x444444, 
                border=8, iterations=3)

Source from the content-addressed store, hash-verified

7from PIL import Image, ImageFilter
8
9def dropShadow( image, offset=(5,5), background=0xffffff, shadow=0x444444,
10 border=8, iterations=3):
11 """
12 Add a gaussian blur drop shadow to an image.
13
14 image - The image to overlay on top of the shadow.
15 offset - Offset of the shadow from the image as an (x,y) tuple. Can be
16 positive or negative.
17 background - Background colour behind the image.
18 shadow - Shadow colour (darkness).
19 border - Width of the border around the image. This must be wide
20 enough to account for the blurring of the shadow.
21 iterations - Number of times to apply the filter. More iterations
22 produce a more blurred shadow, but increase processing time.
23 """
24
25 # Create the backdrop image -- a box in the background colour with a
26 # shadow on it.
27 totalWidth = image.size[0] + abs(offset[0]) + 2*border
28 totalHeight = image.size[1] + abs(offset[1]) + 2*border
29 back = Image.new(image.mode, (totalWidth, totalHeight), background)
30
31 # Place the shadow, taking into account the offset from the image
32 shadowLeft = border + max(offset[0], 0)
33 shadowTop = border + max(offset[1], 0)
34 back.paste(shadow, [shadowLeft, shadowTop, shadowLeft + image.size[0],
35 shadowTop + image.size[1]] )
36
37 # Apply the filter to blur the edges of the shadow. Since a small kernel
38 # is used, the filter must be applied repeatedly to get a decent blur.
39 n = 0
40 while n < iterations:
41 back = back.filter(ImageFilter.BLUR)
42 n += 1
43
44 # Paste the input image onto the shadow backdrop
45 imageLeft = border - min(offset[0], 0)
46 imageTop = border - min(offset[1], 0)
47 back.paste(image, (imageLeft, imageTop))
48
49 return back
50
51if __name__ == "__main__":
52 import sys

Callers 1

recipe-474116.pyFile · 0.85

Calls 5

minFunction · 0.85
maxFunction · 0.50
newMethod · 0.45
pasteMethod · 0.45
filterMethod · 0.45

Tested by

no test coverage detected