Ask Your Question
4

What is the method to create circular thumbnails using PIL?

asked 2023-07-17 19:00:43 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-17 19:07:02 +0000

djk gravatar image

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')
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: 2023-07-17 19:00:43 +0000

Seen: 13 times

Last updated: Jul 17 '23