【问题标题】:.NET Framework and Gif transparency.NET Framework 和 Gif 透明度
【发布时间】:2009-11-25 11:45:52
【问题描述】:

在 Windows 7(和新的图像编解码器:WIC)之前,我使用以下(非常快速但肮脏)的方法来创建以白色为透明色的 Gif 编码图像:

MemoryStream target = new memoryStream(4096);
image.Save(target, imageFormat.Gif);
byte[] data = target.ToArray();

// Set transparency
// Check Graphic Control Extension signature (0x21 0xF9)
if (data[0x30D] == 0x21 && data[0x30E] == 0xF9)
   data[0x313] = 0xFF; // Set palette index 255 (=white) as transparent

此方法有效,因为 .NET 过去使用标准调色板对 Gif 进行编码,其中索引 255 是白色。

但在 Windows 7 中,此方法不再有效。似乎标准调色板已更改,现在索引 251 是白色。但是我不确定。也许新的 Gif 编码器正在根据使用的颜色动态生成调色板?

我的问题:有没有人了解 Windows 7 的新 Gif 编码器,以及什么是使白色透明的好而快速的方法?

【问题讨论】:

    标签: .net gdi+ wic


    【解决方案1】:

    我找到了一种更好的方法,可以将白色设置为 gif 编码图像的透明色。 它似乎适用于由 GDI+ 和 WIC (Windows 7) 编码器编码的 Gif。 以下代码在 Gif 的全局图像表中搜索白色的索引,并使用该索引在 Graphic Control Extension 块中设置透明颜色。

     byte[] data;
    
    // Save image to byte array
    using (MemoryStream target = new MemoryStream(4096))
    {
        image.Save(target, imageFormat.Gif);
        data = target.ToArray();
    }
    
    // Find the index of the color white in the Global Color Table and set this index as the transparent color
    byte packedFields = data[0x0A]; // <packed fields> of the logical screen descriptor
    if ((packedFields & 80) != 0 && (packedFields & 0x07) == 0x07) // Global color table is present and has 3 bytes per color
    {
        int whiteIndex = -1;
        // Start at last entry of Global Color Table (bigger chance to find white?)
        for (int index = 0x0D + (3 * 255); index > 0x0D; index -= 3)
        {
            if (data[index] == 0xFF && data[index + 1] == 0xFF && data[index + 2] == 0xFF)
            {
                whiteIndex = (int) ((index - 0xD) / 3);
                break;
            }
        }
    
        if (whiteIndex != -1)
        {
            // Set transparency
            // Check Graphic Control Extension signature (0x21 0xF9)
            if (data[0x30D] == 0x21 && data[0x30E] == 0xF9)
                data[0x313] = (byte)whiteIndex;
        }
    }
    
    // Now the byte array contains a Gif image with white as the transparent color
    

    【讨论】:

      【解决方案2】:

      您确定这是 Windows 7 的问题,而不是您的代码其他地方的问题吗?

      GIF specification 表明任何索引都可用于提高透明度。您可能需要检查您的图像以确保设置了启用透明度的适当位。如果不是,那么您选择的调色板索引将被忽略。

      【讨论】:

      • 感谢您的回答。事实上,Windows 7 Gif 编码器没有任何问题。只是,与以前的编码器相比,它的行为有所不同:它产生了不同的(但正确的)调色板。因为这个调色板已经改变,我的代码不再工作了。我想知道是否有一种快速的方法来检测调色板中白色的索引是什么,以便我可以将此索引设置为透明色。
      猜你喜欢
      • 2016-01-22
      • 2011-12-24
      • 2015-05-12
      • 2021-03-18
      • 2011-01-22
      • 2019-08-28
      • 2011-02-07
      • 2011-10-18
      • 2013-03-09
      相关资源
      最近更新 更多