Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create circular thumbnails using PIL, you need to follow these steps:

  1. Open the image using PIL's Image.open() method.
  2. Resize the image to the desired size using Image.resize() method.
  3. Create a new image with a circular shape using PIL's Image.new() method and ImageDraw.Draw() method. Set the mode to 'RGBA' to include the alpha channel for transparency.
  4. Draw a circular shape on the new image using ImageDraw.Draw.ellipse() method.
  5. Use the putalpha() method to apply the alpha channel to the circular shape.
  6. Paste the resized image onto the circular shape using Image.paste() method.
  7. Save the circular thumbnail using Image.save() method.

Here is an example code:

from PIL import Image, ImageDraw

# Open the image
image = Image.open('example.jpg')

# Define the radius of the circular thumbnail
radius = 100

# Resize the image
image = image.resize((radius*2, radius*2))

# Create a circular image
mask = Image.new('RGBA', (radius*2, radius*2), (255, 255, 255, 0))
mask_draw = ImageDraw.Draw(mask)
mask_draw.ellipse((0, 0, radius*2, radius*2), fill=(255, 255, 255, 255))

# Apply the alpha channel to the circular image
mask.putalpha(mask_draw)

# Paste the resized image onto the circular image
image.putalpha(mask)

# Save the circular thumbnail as PNG format
image.save('circular_thumbnail.png', format='PNG')