Gamma 值描述人眼對光線亮度的非線性感知曲線。顯示裝置(螢幕)輸出亮度與輸入訊號通常呈冪次關係:
輸出亮度 ∝ 輸入訊號γ
Gamma 校正即透過反函數預先補償,使最終視覺感知趨於線性。
利用 System.Drawing 的 ImageAttributes.SetGamma 方法,由 GDI+ 硬體加速處理:
public static Bitmap KiGamma(Bitmap bmp, float val)
{
if (bmp == null) return null;
if (Math.Abs(val - 1.0f) < float.Epsilon) return bmp; // 無變化快速返回
try
{
Bitmap result = new Bitmap(bmp.Width, bmp.Height);
using (Graphics g = Graphics.FromImage(result))
using (ImageAttributes attr = new ImageAttributes())
{
attr.SetGamma(val, ColorAdjustType.Bitmap);
g.DrawImage(bmp,
new Rectangle(0, 0, bmp.Width, bmp.Height),
0, 0, bmp.Width, bmp.Height,
GraphicsUnit.Pixel, attr);
}
return result;
}
catch
{
return null; // 建議記錄異常而非吞沒
}
}
val = 1.0:無變化val < 1.0:提亮影像(補償螢幕過暗)val > 1.0:壓暗影像(補償螢幕過亮)0.2 ~ 5.0Graphics、ImageAttributes 及時釋放非託管資源ImageAttributes 實例Bitmap.LockBits 直接操作像素對於即時影像處理,預計算 256 級查表更高效:
byte[] gammaLUT = new byte[256];
for (int i = 0; i < 256; i++)
{
gammaLUT[i] = (byte)(255 * Math.Pow(i / 255.0, 1.0 / gamma));
}
// 套用至各色通道