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

再學 GDI+ [90]:TGPImage 獲取調色板資訊 - GetPalette 完整實戰

     編輯:Delphi

演示如何使用 TGPImage.GetPalette 讀取圖像內建調色板,並以 TDrawGrid 可視化顯示所有調色板顏色。

核心流程

  1. GetPaletteSize 取得調色板記憶體大小
  2. GetMem 配置緩衝區
  3. GetPalette 讀取調色板資料
  4. 解析 PColorPalette 結構:Count + Entries[]
  5. TDrawGrid 格狀顯示顏色色塊
  6. FreeMem 釋放緩衝區

關鍵程式碼片段

procedure TForm1.Button1Click(Sender: TObject); 
var Palette: PColorPalette; ColorNum: Integer; Colors: PGPColor; i: Integer; 
begin 
  { 開啟圖片 }
  img.Free; img := TGPImage.Create(OpenDialog1.FileName); 
  
  { 讀取調色板 }
  GetMem(Palette, img.GetPaletteSize); 
  img.GetPalette(Palette, img.GetPaletteSize); 
  
  if Palette^.Count = 0 then begin ShowMessage('此圖片沒有調色板'); Exit; end; 
  
  ColorNum := Palette^.Count; 
  Colors := @Palette.Entries; { 顏色陣列指標 }
  
  { 配置 DrawGrid 顯示 }
  if ColorNum < 16 then DrawGrid1.ColCount := ColorNum else begin DrawGrid1.ColCount := 16; DrawGrid1.RowCount := ColorNum div 16; end; 
  DrawGrid1.Refresh; 
  
  for i := 0 to ColorNum - 1 do 
  begin 
    DrawGrid1.Canvas.Brush.Color := ARGBToColorRef(Colors^); 
    DrawGrid1.Canvas.FillRect(DrawGrid1.CellRect(i mod 16, i div 16)); 
    Inc(Colors); { 指標移至下一顏色 }
  end; 
  
  FreeMem(Palette); 
end;

效果圖

調色板顯示效果

關鍵結構定義

{ 簡化版 }
ColorPalette = record 
  Flags: Integer; 
  Count: Integer; 
  Entries: array[0..0] of ARGB; { 實際大小由 Count 決定 }
end; 
PColorPalette = ^ColorPalette; 

{ ARGB = 32 位無符號整數:Alpha(8) | Red(8) | Green(8) | Blue(8) }

適用格式

  • GIF (索引色,必有調色板)
  • PNG (可選調色板模式)
  • BMP (8位以下必有調色板)
  • TIFF (可選)
  • JPEG (通常無調色板,為直接色)

實用價值

  • 分析索引色圖像色彩分佈
  • 優化調色板 (減少顏色數、重新排序)
  • 格式轉換時保持調色板一致性
  • 復古風格/像素藝術圖像處理

掌握 GetPalette 低級 API,能處理現代高級 API 難以觸及的索引色圖像細節需求。

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