1 | initial version |
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:
Image.open()
function.'L'
mode) with all pixels set to 0 (black) initially.ImageDraw
module. The circle is centered within the mask image.image.convert()
function. The alpha channel is initialized to 0 for all pixels.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.image.save()
function. The image is saved in PNG format to support transparency.