Simple image masking with PIL
If you ever wanted to create custom images that are all masked by a surrounding frame, here is a solution using python (using PIL instead of a system call running ImageMagick). This example illustrates, how you use png-transparency. I’m using this within django for creating special thumbnails of uploaded video files. Maybe someone feels like writing a general django template-tag for that.
from PIL import Image, ImageOps, ImageFilter
# the image we want to paste in the transparent mask
background = Image.open("my_background_image.jpg")
# the mask, where we insert our image
mask = Image.open("my_mask.png")
# mask, that we overlay
frame_mask = Image.open("my_frame_mask.png")
# smooth the mask a little bit, if you want
# mask = mask.filter(ImageFilter.SMOOTH)
# resize/crop the image to the size of the mask-image
cropped_image = ImageOps.fit(background, mask.size, method=Image.ANTIALIAS)
# get the alpha-channel (used for non-replacement)
cropped_image = cropped_image.convert("RGBA")
r,g,b,a = mask.split()
# paste the frame mask without replacing the alpha mask of the mask-image
cropped_image.paste(frame_mask, mask=a)
cropped_image.save("my_generated_image.png")




19. April 2008 um 23:33
Do the images all have to be the same size?
26. April 2008 um 21:56
The background images don’t need to be the same size. Just the image masks.
2. June 2008 um 19:41
That’s cool! This is exactly what I needed one year before for one project. As I couldn’t find such a nice solution, I coded my own cropping and resizing and per-pixel-based masking instead :).