0

I have a source file image.ico of any size and want to create a thumbnail. This is the code i am using right now:

    converted_file = cStringIO.StringIO()
    thumb = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
    thumb.save(converted_file, format='png')

I chose png as extension because PIL does not support ico files which could be the culprit. It works beside the fact that transparency is not applied. Parts with alpha=0 are rendered black instead of being transparent. How can i fix this behavior?

/edit

I also tried (see this answer):

    converted_file = cStringIO.StringIO()
    thumb = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
    background = Image.new('RGBA', (width, height), (255, 255, 255, 0))
    background.paste(thumb, box = (0, 0, width, height))
    background.save(converted_file, format='png')

Same effect.

Community
  • 1
  • 1
Alp
  • 29,274
  • 27
  • 120
  • 198
  • How are you looking at the image? Try opening it in Chrome for example. Do the transparent areas still appear to be black? –  Jul 07 '13 at 22:29
  • yes. this answer may be the solution: http://stackoverflow.com/questions/987916/how-to-determine-the-transparent-color-index-of-ico-image-with-pil – Alp Jul 07 '13 at 22:32

1 Answers1

1

The Problem is indeed that PIL does not know how to exactly read ICO files. There are two possibilities how to fix this:

  1. Add a plugin to PIL that registers the ICO format
  2. Use Pillow, a fork of PIL that is more frequently updated

I chose to use Pillow which is also Python 3 compatible and has some more goodies.

1. PIL Plugin

Save the Win32IconImagePlugin somewhere in your project. After importing the PIL Image class, import the plugin to register ICO support:

from PIL import Image
import Win32IconImagePlugin

There you go, now you can use the right format:

thumb.save(converted_file, format='ico')

2. Pillow

Pillow has builtin support for ICO images.

Just remove pil and install pillow:

pip uninstall pil
pip install pillow

Be sure to change all global pil imports:

import Image, ImageOps

to

from PIL import Image, ImageOps

There you go, now you can use the right format:

thumb.save(converted_file, format='ico')
Alp
  • 29,274
  • 27
  • 120
  • 198