Skip to content

Instantly share code, notes, and snippets.

@mapi68
Last active March 11, 2024 07:10
Show Gist options
  • Save mapi68/6b7312d8fec257be7a34d7493a3f35fc to your computer and use it in GitHub Desktop.
Save mapi68/6b7312d8fec257be7a34d7493a3f35fc to your computer and use it in GitHub Desktop.
This Python script utilizes the Python Imaging Library (PIL) to create a multi-size icon file (icon.ico) from a source image (icon.png).
from PIL import Image
# Define dimensions for various icon images
sizes = [(16, 16), (32, 32), (48, 48), (256, 256)]
try:
# Open the source image (replace 'icon.png' with the path to your image file)
source_image = Image.open("icon.png")
# Check if the source image size is at least 256x256
if source_image.size[0] < 256 or source_image.size[1] < 256:
raise ValueError("Error: Minimum 'icon.png' size should be 256x256.")
except FileNotFoundError:
print("Error: 'icon.png' file not found.")
# You can add additional handling or exit the script if needed.
exit()
except ValueError as e:
print(e)
# You can add additional handling or exit the script if needed.
exit()
# Create a new icon file
icon = Image.new("RGBA", (sizes[-1][0], sizes[-1][1]))
# Resize and paste the source image into the icon file for each size
for size in sizes:
resized_image = source_image.resize(size, Image.LANCZOS)
offset = ((sizes[-1][0] - size[0]) // 2, (sizes[-1][1] - size[1]) // 2)
icon.paste(resized_image, offset)
# Save the icon file
icon.save("icon.ico", format="ICO")
# Print a message if saving is successful
print("Icon file 'icon.ico' saved successfully.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment