Ask Your Question
3

How can I use the Python PIL library to round the corners of an image by applying a mask?

asked 2022-07-30 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-02-11 21:00:00 +0000

huitzilopochtli gravatar image

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.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-30 11:00:00 +0000

Seen: 9 times

Last updated: Feb 11 '23