【问题标题】:ImageOps.fit() with transparent parts in ICO imagesImageOps.fit() 在 ICO 图像中具有透明部分
【发布时间】:2013-07-07 22:19:09
【问题描述】:

我有一个任意大小的源文件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 的部分被渲染为黑色而不是透明的。我该如何解决这个问题?

/编辑

我也试过了(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')

同样的效果。

【问题讨论】:

  • 你看图片怎么样?例如,尝试在 Chrome 中打开它。透明区域是否仍然显示为黑色?
  • 是的。这个答案可能是解决方案:stackoverflow.com/questions/987916/…

标签: python python-imaging-library alpha


【解决方案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 拥有builtin support for ICO images

只需卸下 pil 并安装枕头:

pip uninstall pil
pip install pillow

确保更改所有全局 pil 导入:

import Image, ImageOps

from PIL import Image, ImageOps

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 2017-03-21
    • 2011-12-06
    • 2019-09-21
    • 2021-12-30
    • 2014-10-06
    • 2019-04-01
    相关资源
    最近更新 更多