首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi GDI+ 學習筆記 (31):影像顏色轉換 (TGPImageAttributes)

     編輯:Delphi

ColorMatrix 實作顏色空間線性變換

TGPImageAttributes 配合 5×5 TColorMatrix 可對影像進行紅/綠/藍/Alpha 通道的縮放、平移、混合、灰階、負片、色調旋轉等線性運算。本範例示範在繪圖時套用 ColorMatrix,將紅色通道加入常數位移,產生紅色色調偏移效果。

正常繪圖 (無轉換)


uses GDIPAPI, GDIPOBJ;

procedure TForm1.FormPaint(Sender: TObject);
var
  g: TGPGraphics;
  img: TGPImage;
begin
  g := TGPGraphics.Create(Canvas.Handle);
  img := TGPImage.Create('c:\temp\test.png');
  g.DrawImage(img, 0, 0, img.GetWidth, img.GetHeight);
  img.Free;
  g.Free;
end;

原始影像

套用 ColorMatrix (紅色通道 +1.0 位移)


uses GDIPAPI, GDIPOBJ;

procedure TForm1.FormPaint(Sender: TObject);
var
  g: TGPGraphics;
  img: TGPImage;
  imgAtt: TGPImageAttributes;
const
  ColorMatrix: TColorMatrix = (
    (1.0, 0.0, 0.0, 0.0, 0.0),
    (0.0, 1.0, 0.0, 0.0, 0.0),
    (0.0, 0.0, 1.0, 0.0, 0.0),
    (0.0, 0.0, 0.0, 1.0, 0.0),
    (1.0, 0.0, 0.0, 0.0, 1.0)  // 第 5 列:平移向量 (R+1, G+0, B+0, A+0, W+1)
  );
begin
  g := TGPGraphics.Create(Canvas.Handle);
  img := TGPImage.Create('c:\temp\test.png');
  imgAtt := TGPImageAttributes.Create;
  imgAtt.SetColorMatrix(ColorMatrix, ColorMatrixFlagsDefault, ColorAdjustTypeDefault);
  g.DrawImage(
    img,
    MakeRect(0, 0, img.GetWidth, img.GetHeight),
    0, 0, img.GetWidth, img.GetHeight,
    UnitPixel,
    imgAtt
  );
  imgAtt.Free;
  img.Free;
  g.Free;
end;

色調偏移效果

ColorMatrix 結構說明

  • 前 4×4:縮放/旋轉/剪切 (R,G,B,A 通道線性組合)
  • 第 5 列 (索引 4):平移向量 (Offset),對應 R,G,B,A,W 的常數加值
  • 矩陣乘法:[R' G' B' A' 1] = [R G B A 1] × Matrix

常見矩陣範例

效果矩陣關鍵值
灰階R=G=B=0.299/0.587/0.114
負片對角 -1.0,平移 +1.0
紅色濾鏡G=B 行歸零,R 行保留
透明度 50%A 對角 0.5
色調旋轉RGB 3×3 旋轉子矩陣

掌握 ColorMatrix 即掌握 GDI+ 核心影像處理能力,所有濾鏡效果皆可由此推導。

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