Archiv der Kategorie ‘Django‘

 
 

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")

The image for the background

The background image we want to insert

The masks

Mask for inserting the imageMask for the frame

And here the resulting film strip

The resulting film strip