0

我有一个image.ico任意大小的源文件并想创建一个缩略图。这是我现在使用的代码:

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

我选择png作为扩展名是因为 PIL 不支持ico可能是罪魁祸首的文件。除了不应用透明度这一事实之外,它还有效。alpha=0 的部分被渲染为黑色而不是透明的。我该如何解决这种行为?

/编辑

我也试过(见这个答案):

    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')

一样的效果。

4

1 回答 1

1

问题确实是 PIL 不知道如何准确读取 ICO 文件。如何解决此问题有两种可能性:

  1. 向 PIL 添加一个注册 ICO 格式的插件
  2. 使用 Pillow,PIL 的一个分支,更新更频繁

我选择使用 Pillow,它也兼容 Python 3,并且有更多好东西。

1.PIL插件

将Win32IconImagePlugin保存在项目中的某个位置。导入 PIL Image 类后,导入插件注册 ICO 支持:

from PIL import Image
import Win32IconImagePlugin

好了,现在您可以使用正确的格式:

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

2.枕头

Pillow内置了对 ICO 图像的支持

只需卸下 pil 并安装枕头:

pip uninstall pil
pip install pillow

请务必更改所有全局 pil 导入:

import Image, ImageOps

from PIL import Image, ImageOps

好了,现在您可以使用正确的格式:

thumb.save(converted_file, format='ico')
于 2013-07-09T08:22:38.363 回答