2009-11-25 46 views
1

的Windows 7(和新的圖像編解碼器:WIC)之前我用下面的(非常快但髒)方法創建與白色爲透明色GIF格式編碼的圖像:.NET框架和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編碼器有所瞭解,以及怎樣才能讓顏色變得透明?

回答

3

我已經找到了一種更好的方法來將白色設置爲gif編碼圖像的透明色。 它似乎適用於由GDI +和WIC(Windows 7)編碼器編碼的Gif。 以下代碼在Gif的全局圖像表中搜索白色的索引,並使用此索引在圖形控制擴展塊中設置透明顏色。

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 
0

你確定這是一個Windows 7的問題,而不是你的代碼在其他地方的問題?

GIF specification表明任何索引都可以用於透明度。您可能需要檢查圖像以確保啓用適當的位啓用透明度。如果不是,那麼您選擇的調色板索引將被忽略。

+0

感謝您的回答。實際上Windows 7 Gif編碼器沒有任何問題。只有它與以前的編碼器相比表現不同:它會產生一個不同的(但是正確的)調色板。由於此調色板已更改,我的代碼不再工作。我想知道是否有一種快速的方法來檢測調色板中白色的索引是什麼,所以我可以將此索引設置爲透明顏色。 – Corne 2009-11-25 12:42:49