Question

I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files.

Was it helpful?

Solution

According to Wikipedia modern browsers can handle favicons in PNG format, so maybe you could just generate that?

Alternatively the ICO article describes the format...

OTHER TIPS

You can use Pillow:

from PIL import Image
filename = r'logo.png'
img = Image.open(filename)
img.save('logo.ico')

Optionally, you may specify the icon sizes you want:

icon_sizes = [(16,16), (32, 32), (48, 48), (64,64)]
img.save('logo.ico', sizes=icon_sizes)

The Pillow docs say that by default it will generate sizes [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)] and any size bigger than the original size or 255 will be ignored.

Yes, it is in the Read-only section of the docs, but it works to some extent.

Perhaps the following would work:

  • Generate your icon image using PIL
  • Convert the image to .ico format using the python interface to ImageMagick, PythonMagick

I have not tried this approach. The ImageMagick convert command line program was able to convert a .png file to .ico format, so at least ImageMagick supports the .ico format.

I don't know if this applies for all cases, but on WinXP an .ico can be a bmp of size 16x16, 32x32 or 64x64. Just change the extension to ico from bmp and you're ready to go.

If you have imageio, (probably the best library for reading/writing images in Python), you can use it:

import imageio

img = imageio.imread('logo.png')
imageio.imwrite('logo.ico', img)

Install is as easy as

pip install imageio
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top