如何用PIL确定ICO图像的透明颜色指数?

2024-02-21

具体来说,这是来自 .ico 文件,因此不存在像 gif 中那样的“透明”“信息”属性。下面的示例说明了使用正确的透明度索引“0”将 Yahoo! 的图标转换为 png,这是我猜测的。如何检测 ico 实际上是透明的并且透明度索引为 0 ?

import urllib2
import Image
import StringIO

resp = urllib2.urlopen("http://www.yahoo.com/favicon.ico")
image = Image.open(StringIO.StringIO(resp.read()))

f = file("test.png", "w")

# I guessed that the transparent index is 0.  how to
# determine it correctly ?
image.save(f, "PNG", quality=95, transparency=0)

看起来有人认识到 PIL 并没有真正正确地读取 ICO(在将其源代码与 ICO 格式的一些研究进行协调后,我可以看到同样的事情 - 有一个 AND 位图决定透明度) 并想出了这个扩展:

http://www.djangosnippets.org/snippets/1287/ http://www.djangosnippets.org/snippets/1287/

因为这对于非 django 应用程序很有用,所以我在此处重新发布了对其异常抛出的一些调整:

import operator
import struct

from PIL import BmpImagePlugin, PngImagePlugin, Image


def load_icon(file, index=None):
    '''
    Load Windows ICO image.

    See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format
    description.
    '''
    if isinstance(file, basestring):
        file = open(file, 'rb')

    try:
        header = struct.unpack('<3H', file.read(6))
    except:
        raise IOError('Not an ICO file')

    # Check magic
    if header[:2] != (0, 1):
        raise IOError('Not an ICO file')

    # Collect icon directories
    directories = []
    for i in xrange(header[2]):
        directory = list(struct.unpack('<4B2H2I', file.read(16)))
        for j in xrange(3):
            if not directory[j]:
                directory[j] = 256

        directories.append(directory)

    if index is None:
        # Select best icon
        directory = max(directories, key=operator.itemgetter(slice(0, 3)))
    else:
        directory = directories[index]

    # Seek to the bitmap data
    file.seek(directory[7])

    prefix = file.read(16)
    file.seek(-16, 1)

    if PngImagePlugin._accept(prefix):
        # Windows Vista icon with PNG inside
        image = PngImagePlugin.PngImageFile(file)
    else:
        # Load XOR bitmap
        image = BmpImagePlugin.DibImageFile(file)
        if image.mode == 'RGBA':
            # Windows XP 32-bit color depth icon without AND bitmap
            pass
        else:
            # Patch up the bitmap height
            image.size = image.size[0], image.size[1] >> 1
            d, e, o, a = image.tile[0]
            image.tile[0] = d, (0, 0) + image.size, o, a

            # Calculate AND bitmap dimensions. See
            # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage
            # for description
            offset = o + a[1] * image.size[1]
            stride = ((image.size[0] + 31) >> 5) << 2
            size = stride * image.size[1]

            # Load AND bitmap
            file.seek(offset)
            string = file.read(size)
            mask = Image.fromstring('1', image.size, string, 'raw',
                                    ('1;I', stride, -1))

            image = image.convert('RGBA')
            image.putalpha(mask)

    return image
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用PIL确定ICO图像的透明颜色指数? 的相关文章

随机推荐

  • 具有动态数组的 VBA 字典

    我正在尝试创建包含动态数组的动态字典 电子表格中的示例行 Facility Name Contact Name Contact Role 设施和联系人之间的关系是M2M 我想重新创建一个如下所示的工作表 Contact Name Facil
  • 持久化图形数据 (Java)

    我有一个利用图形 树状 自定义结构的应用程序 这些结构不是真正的树 但几乎所有东西都连接在一起 数据量也很大 可以存在数百万个节点 树节点的类型可以不同 以使其更有趣 继承 我不想改变数据结构来适应持久性存储 我想保留这些数据而不需要太多额
  • 在两个不同模式中使用两个同名表时避免 Hibernate Annotation Exception

    我有两个表 都在两个不同的模式中命名为 Language 我们将它们称为 schema1 和 schema2 当我注释每个表的模型时 我的代码如下所示 实体 Table 名称 语言 目录 模式1 公开课语言 Entity Table nam
  • 资源 FullCalendar 中的固定列宽

    我正在使用支持资源视图的 FullCalendar 特殊版本 http tux fi jarnok fullcalendar resourceviews http tux fi jarnok fullcalendar resourcevie
  • SQL删除表中不重复的条目

    我有一个有两列的表格CountryCode CountryName 中存在重复条目countrycode 但我想删除不重复的条目并保留重复的行countrycode柱子 所以我想写一个SQL语句来做到这一点 我想我必须使用having 但不
  • Ruby on Rails 生成视图

    有没有办法使用railsgenerate命令单独生成视图 我也愿意安装一个 gem 来完成现有的任务 基本上 脚手架命令给了我太多的东西 我宁愿手动编写我的控制器 但是 使用记录表编写索引视图的效率不是很高 您可以使用控制器生成器生成控制器
  • Firefox 扩展将 Javascript 数组作为对象发送

    我在将 JavaScript 数组传递给我正在编写的附加组件时遇到问题附加生成器 https builder addons mozilla org 为了进行通信 我使用事件并使用数组发送事件 但附加组件 内容脚本 获取一个对象 而不是数组
  • 尝试获取最小整数

    所以我有4个清单 我想找出哪个 list size 是最低的 我可以找到最低的 但有些结果是相同的 这是 我拥有的 if EAmount lt DAmount EAmount lt GAmount EAmount lt IAmount Fi
  • 如何解决 flutter firebase 中的此 NoSuchMethodError

    我有这段代码 应该返回 userId 问题是它返回 null 因为用户已注销 override void initState TODO implement initState super initState try widget auth
  • 如何将字符串转换为浮点数? [复制]

    这个问题在这里已经有答案了 可能的重复 在 Objective C 中将字符串转换为浮点数 https stackoverflow com questions 3191034 convert string to float in objec
  • Grunt.js:在任务完成之前修改文件后立即触发 livereload

    我正在使用 Grunt 来编译带有指南针的 CSS 并触发浏览器 livereload 这些是我的手表任务 watch styles options spawn false files assetsDir scss dev min scss
  • React - ComponentDidMount 没有从 Redux 状态获取值

    I am getting the Redux state updated correctly Here is what the Redux state of updateNeeded is In this case it is true 我
  • 使用 SSL 从 NXlog 传送到 Logstash

    我让 NXLog 将我的 Windows 事件发送到另一台仅在 TCP 中正常工作的 Logstash 机器 但我想使用自签名证书加密流量 我想我对 SSL 有基本的了解 但对 NXLog 文档感到困惑 NXLog om ssl 文档显示
  • 将自定义命令添加到 qmake 中的现有目标

    有没有办法指定 在 pro文件中 要添加到标准目标的额外命令Makefile that qmake产生 例如 考虑distclean 可能需要额外的命令来 Remove files 从源树中清除运行时生成的输出文件 Etc 我想使用普通目标
  • 在其他导入与 pep8 发生冲突之前需要 matplotlib.use。忽略还是修复?

    我有一个 Python 脚本 其开头如下 usr bin env python import matplotlib matplotlib use Agg from matplotlib dates import strpdate2num i
  • 无法获取通用 ResponseEntity,其中 T 是通用类“SomeClass

    请帮我得到一个ResponseEntity
  • 如何使用 C# 实现 SAP GUI 自动化

    我想使用 C 语言自动化 SAP GUI 窗口 我可以用 VBScript 做到这一点 但代码重用很糟糕 此外 我想使用线程而不是运行 80 个或更多进程 在哪里可以找到有关如何执行此操作的任何文档和示例 这是我正在使用的代码 基本上 我面
  • 使用 PIL.Image 和 ctypes 进行像素操作

    我有一个 C 函数 可以对 8 位 RGB 值的原始 2D 数组进行一些像素操作 我得到的答复是c ubyte大批 我的代码大致如下 from ctypes import cdll CDLL Structure byref c utype
  • wix v3.8重大升级时如何保留配置文件?

    我想在 msi 安装程序进行重大升级时保留配置文件 对于配置文件 我在安装时进行了更改 代码如下
  • 如何用PIL确定ICO图像的透明颜色指数?

    具体来说 这是来自 ico 文件 因此不存在像 gif 中那样的 透明 信息 属性 下面的示例说明了使用正确的透明度索引 0 将 Yahoo 的图标转换为 png 这是我猜测的 如何检测 ico 实际上是透明的并且透明度索引为 0 impo