GIF (Graphics Interchange Format) 使用 8-bit 索引色,最多 256 色,採 LZW 無損壓縮。檔頭含調色板,定義透明色索引。GIF 僅支援全透明/不透明,無半透明;單一調色板僅能設一個透明色索引。
LockBits 處理 GIF 時建議鎖定為 Format8bppIndexed 保留調色板。以下代碼示範建立帶指定透明索引的 GIF:
public static unsafe void ConvertTransparancyGif(int colorIndex, string baseFile, string outputFile)
{
using (FileStream fs = new FileStream(baseFile, FileMode.Open, FileAccess.Read))
{
Bitmap img = (Bitmap)Image.FromStream(fs, false, false);
int w = img.Width, h = img.Height;
Bitmap result = new Bitmap(w, h, PixelFormat.Format8bppIndexed);
ColorPalette pal = result.Palette;
int n = 0;
foreach (Color c in img.Palette.Entries) pal.Entries[n++] = Color.FromArgb(255, c);
// 設定透明色(Alpha=0)
pal.Entries[colorIndex] = Color.FromArgb(0, pal.Entries[colorIndex]);
result.Palette = pal;
// 複製像素資料
BitmapData src = img.LockBits(new Rectangle(0,0,w,h), ImageLockMode.ReadOnly, img.PixelFormat);
BitmapData dst = result.LockBits(new Rectangle(0,0,w,h), ImageLockMode.WriteOnly, result.PixelFormat);
byte* pSrc = (byte*)src.Scan0;
byte* pDst = (byte*)dst.Scan0;
int offset = src.Stride - w;
for (int y=0; y
關鍵點: 讀取時不可 new Bitmap(img)(會丟失調色板),需從串流建立。Bitmap.MakeTransparent() 僅對 PNG 有效。
參考 KB 319061:MSDN