天天看點

如何擷取圖檔中第一個像素的顔色值?

unit Unit1;  
  
interface  
  
uses  
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  
  Dialogs, StdCtrls;  
  
type  
  TForm1 = class(TForm)  
    Button1: TButton;  
    Button2: TButton;  
    procedure Button1Click(Sender: TObject);  
    procedure Button2Click(Sender: TObject);  
  end;  
  
var  
  Form1: TForm1;  
  
implementation  
  
{$R *.dfm}  
  
const BmpPath = 'C:/Temp/Test.bmp'; {測試用圖檔}  
  
{使用 Canvas.Pixels 屬性}  
procedure TForm1.Button1Click(Sender: TObject);  
var  
  bit: TBitmap;  
  clr: TColor;  
begin  
  bit := TBitmap.Create;  
  bit.LoadFromFile(BmpPath);      {載入圖檔}  
  clr := bit.Canvas.Pixels[0, 0]; {擷取第一像素的顔色值}  
  ShowMessageFmt('$%.6x', [clr]); {顯示為十六進制字元串看看}  
  //Self.Color := clr;            {可用窗體呈現一下}  
  bit.Free;  
end;  
  
{使用 API 函數 GetPixel}  
procedure TForm1.Button2Click(Sender: TObject);  
var  
  bit: TBitmap;  
  clr: TColor;  
begin  
  bit := TBitmap.Create;  
  bit.LoadFromFile(BmpPath);               {載入圖檔}  
  clr := GetPixel(bit.Canvas.Handle, 0, 0);{擷取第一像素的顔色值}  
  ShowMessageFmt('$%.6x', [clr]);          {顯示為十六進制字元串看看}  
  //Self.Color := clr;                     {可用窗體呈現一下}  
  bit.Free;  
end;  
  
end