Ask Your Question

Revision history [back]

Here is an example code using the Python PIL library to round the corners of an image by applying a mask:

from PIL import Image, ImageDraw

# Open image file
image_path = "path/to/image.jpg"
image = Image.open(image_path)

# Create mask with rounded corners
mask_size = min(image.size)
mask = Image.new('L', (mask_size, mask_size), 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0, mask_size, mask_size), fill=255)
mask_corner = (image.size[0] - mask_size) // 2, (image.size[1] - mask_size) // 2
mask_image = Image.new('L', image.size, 0)
mask_image.paste(mask, mask_corner)

# Apply mask to image
image = image.convert('RGBA')
image.putalpha(mask_image)

# Save modified image
image.save("path/to/output.png")

Explanation:

  1. Open the image file using the Image.open() function.
  2. Create a mask image with rounded corners. The mask size is set to be the minimum of the image width and height to ensure that the mask fits within the image boundaries. The mask is created as a grayscale image ('L' mode) with all pixels set to 0 (black) initially.
  3. Draw a white circle (255 value) on the mask using the ImageDraw module. The circle is centered within the mask image.
  4. Estimate the corner of the mask image by computing the difference between the image and mask sizes and dividing by 2.
  5. Create a new mask image that matches the size of the original image and paste the rounded mask onto it. The mask is positioned at the estimated corner coordinates.
  6. Convert the original image to RGBA mode and add an alpha channel using the image.convert() function. The alpha channel is initialized to 0 for all pixels.
  7. Paste the mask image onto the original image using the image.putalpha() function. This applies the mask to the image, and non-masked pixels remain fully opaque while masked pixels become increasingly transparent based on the mask pixel values.
  8. Save the modified image using the image.save() function. The image is saved in PNG format to support transparency.