Title: Make elliptical images in Python
This example lets you load an image and save an elliptical version where the pieces outside the elliptical area are transparent.
The process is actually not too complicated if you know a bit about using PIL. The idea is to make an elliptical mask image and then copy its alpha (transparency) channel to the image.
Ellipsifying Images
The following elliptical_image function converts an image into an elliptical version.
def elliptical_image(image):
'''Return an elliptical copy of the image.'''
# Make an elliptical mask image, initially transparent.
mask = Image.new('L', (image.width, image.height), 0)
dr = ImageDraw.Draw(mask)
dr.ellipse((0, 0, image.width-1, image.height-1),
fill='white', outline=None)
# Copy the image so we don't mess up the original.
image = image.copy()
# Use the mask to set the image's transparency.
image.putalpha(mask)
return image
The function first makes a mask image the same size as the original. Initially the mask is transparent (color 0) but the code then draws an opaque (white) ellipse on it.
The code then creates a copy of the original image so it doesn't mess it up. It then calls the copy's putalpha method to copy the mask's alpha channel onto the image. (The call to putalpha works in place so that's why the function makes a copy of the image.)
The function then returns the modified copy.
Conclusion
The elliptical_image function works by making the areas outside of the image's elliptical center transparent. It doesn't need to modify the image's pixels separately, so it's super fast.
Download the example to experiment with it and to see additional details.
|