SoFunction
Updated on 2025-04-11

Python sample code for converting PNG images to ICO icons using PIL library

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

  1. Import library: First import the PIL libraryImageModule.
  2. Define functions: Define a namepng_to_icoThe function, receives three parameters: PNG image pathpng_path, output ICO picture pathico_pathand the list of icon sizes contained in the ICO filesizes(Default is [(64, 64), (128, 128), (256, 256)]).
  3. Open the picture:useFunction opens the PNG image file.
  4. Save as ICO file: CalledMethod: Save the image in ICO format and specifyformatThe parameters are'ICO', and passsizesParameters 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!