首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

GDI+ 進階議題:透明度處理(六)——GIF 透明色與調色板操作

     編輯:關於.NET

6.2 GIF 透明色處理

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved