WinForm/WPF 常見 BackColor.Transparent、Form.Opacity 皆屬應用層封裝。本文從 GDI+ 底層探討。
PixelFormat.Format32bppArgb 含 A/R/G/B 四通道,A 為透明度(0 全透明、255 不透明)。此概念由 Catmull 與 Smith 於 70 年代初提出,透過 Alpha 混合演算法實現前景與背景疊加。詳細原理。
public unsafe Bitmap GenerateBitmap(byte alpha)
{
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
Image img = Image.FromStream(fs, false, false);
Bitmap bmp = new Bitmap(img);
img.Dispose(); fs.Close();
int w = bmp.Width, h = bmp.Height;
BitmapData bmData = bmp.LockBits(new Rectangle(0,0,w,h), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
byte* p = (byte*)bmData.Scan0;
int offset = bmData.Stride - w * 4; // 每像素 4 bytes
for (int y=0; y
注意: 小端序下記憶體順序為 B、G、R、A,故 Alpha 索引為 p[3]。Format32bppPArgb 為預乘 Alpha 格式,RGB 已乘入 Alpha,減少運算。
Format32bppRgb,第 4 byte 棄用。Format24bppRgb,Alpha 丟失。Format8bppIndexed,Alpha 無效(下節討論 GIF 透明處理)。標準規定 BMP/JPEG 不支援透明通道,GIF 雖支援透明但機制不同(索引色)。