introduction
In software development and website design, ICO icons are a commonly used image format, especially suitable for scenarios such as application icons, web favorites icons, etc. This article will introduce how to convert PNG images to icon files in ICO format using Python's PIL (Python Imaging Library) library.
Preparation
First, make sure that the PIL library is already installed in your Python environment. If it has not been installed, you can install it through the pip command:
pip install Pillow
Pillow is a friendly branch of PIL, it adds some new features and fixes some bugs, so it is more recommended to use Pillow.
Code parsing
Here is a complete Python script for converting PNG images into ICO icon files:
from PIL import Image def png_to_ico(png_path, ico_path, sizes=[(64, 64), (128, 128), (256, 256)]): """ Convert PNG images to ICO format :param png_path: picture path :param ico_path: Output ICO image path :param sizes: List of icon sizes contained in ICO files """ # Open PNG picture img = (png_path) # Save as ICO file, specify the format and size list (ico_path, format='ICO', sizes=sizes) # Example usagepng_path = r'D:\test_pic\' # Image pathico_path = r'D:\test_pic\20250307_output.ico' # Saved ICO picture pathpng_to_ico(png_path, ico_path)
Code parsing:
-
Import library: First import the PIL library
Image
Module. -
Define functions: Define a name
png_to_ico
The function, receives three parameters: PNG image pathpng_path
, output ICO picture pathico_path
and the list of icon sizes contained in the ICO filesizes
(Default is [(64, 64), (128, 128), (256, 256)]). -
Open the picture:use
Function opens the PNG image file.
-
Save as ICO file: Called
Method: Save the image in ICO format and specify
format
The parameters are'ICO'
, and passsizes
Parameters specify the list of icon sizes contained in the ICO file.
Practical operation
You can follow the example code above, replace the PNG image path and output ICO image path with your own file path, and adjust the ICO icon size list as needed. After running the code, you will find the generated ICO icon file under the specified path.
Results Display
The generated ICO icon file will contain multiple size icons you specify, which can be used in different application scenarios, such as application icons, web favorites icons, etc.
Conclusion
Through this tutorial, you should have learned how to use the PIL library to convert PNG images to icon files in ICO format. This trick is very useful in many scenarios, especially when developing Windows applications or designing web pages.
The above is the detailed content of the sample code for Python using the PIL library to convert PNG images to ICO icons. For more information about converting Python PNG images to ICO icons, please pay attention to my other related articles!