[Image-SIG] How to "crop" along a mask?

Nils de Reus nils.de.reus at ivm.vu.nl
Tue Jan 26 11:02:58 CET 2010

What you describe is not cropping, but rather the setting of an alpha mask. Here is the simple case for if all your images are the same size as your template, and only the template has transparancy information:

# Get the Alpha band from the template

tmplt = Image.open('template.png')
A = tmplt.split()[3]

# Get the R, G, B bands from the image to apply the alpha to

im = Image.open('myimage.png')
[R, G, B] = im.split()

# Combine the RGB from the image with the A from the template

newimg = Image.merge('RGBA', (R, G, B, A))

# Write the result back to disk under another name


To get from the simple case to more general uses:
- If your images are not all the same size, you need to think about how you want to scale the template to match.
- If your other images do have some other transparency of their own, combine the A band from the image with the A band from the template before you merge everything back together.

Hope this helps, kind regards,

I'm trying to take a group of pictures and give them rounded edges. I have a source image (a rectangle with rounded edges, transparent PNG) and I'd like to use this as a template. All the target images would become transparent wherever this source image is transparent.

In other words, I'd be making the same region of the target image transparent as is transparent in the source image.

Any tips for accomplishing this?

More information about the Image-SIG mailing list