Skip to content

Instantly share code, notes, and snippets.

@OldPanda
Created December 8, 2023 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OldPanda/55f5a40f152cb94c29e2ce099d25dbd8 to your computer and use it in GitHub Desktop.
Save OldPanda/55f5a40f152cb94c29e2ce099d25dbd8 to your computer and use it in GitHub Desktop.
Script to crop icon image with size 1024x1024 to 16x16, 32x32, 48x48, and 128x128, and cut the icon to be a rounded square.
from PIL import Image, ImageDraw, ImageOps
corner_radius = 100
def crop_to_circle(image_path, output_path, size):
original_image = Image.open(image_path)
square_image = ImageOps.fit(original_image, (1024, 1024), method=0, bleed=0.0, centering=(0.5, 0.5))
rounded_image = Image.new("RGBA", square_image.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(rounded_image)
draw.rounded_rectangle([(0, 0), square_image.size], corner_radius, fill=(255, 255, 255, 255))
rounded_image.paste(square_image, mask=square_image)
resized_image = square_image.resize((size, size), Image.DEFAULT_STRATEGY)
data = resized_image.getdata()
new_data = []
for item in data:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
new_data.append((255, 255, 255, 0)) # change white color to transparent
else:
new_data.append(item)
resized_image.putdata(new_data)
resized_image.save(output_path)
sizes = [128, 48, 32, 16] # <== change the list if you'd like other sizes
for size in sizes:
output_path = f"icon_{size}.png"
crop_to_circle("/path/to/your/icon/icon_1024.png", output_path, size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment