How to get the RGB value of a pixel under the mouse cursor #95

Question
How can I get the hex RGB value of the pixel under the cursor? I want to be able to do this when the cursor is over an image.

Mouse movement:

procedure TForm1.ImageMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
var
  ColNumb: TColor;
  R, G, B: Byte;
begin
  ColNumb := Image.Canvas.Pixels[X, Y]; {The image can't be a JPG}
  GetRGB(ColNumb, R, G, B);
  {Here are the RGB values you need}
end;

The GetRGB procedure:

procedure GetRGB(Col: TColor; var R, G, B: Byte);
var
  Color: $0..$FFFFFFFF;
begin
  Color := ColorToRGB(Col);
  R := ($000000FF and Color);
  G := ($0000FF00 and Color) Shr 8;
  B := ($00FF0000 and Color) Shr 16;
end;

Demo code

A ready made project containing this demo code is available. View the project.

This demo lets you move the mouse over an image control that is displaying a bitmap and displays the red, green and blue values of the pixel under the cursor.

Start a new Delphi VCL application and do the following:

  • Name the default form "Form1" and save the unit as Unit1.pas.
  • Drop a TImage component on the form and name it "Image".
  • Create an OnMouseMove event handler for the image control.
  • Load a suitable bitmap into the image control's Picture property.
  • Drop three TLabels on the form.

Now code the form unit as follows:

unit Unit1;

interface

uses
  SysUtils, Forms, StdCtrls, Graphics, Classes, Controls, ExtCtrls;

type
  TForm1 = class(TForm)
    Image: TImage;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    procedure ImageMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure GetRGB(Col: TColor; var R, G, B: Byte);
var
  Color: $0..$FFFFFFFF;
begin
  Color := ColorToRGB(Col);
  R := ($000000FF and Color);
  G := ($0000FF00 and Color) Shr 8;
  B := ($00FF0000 and Color) Shr 16;
end;

procedure TForm1.ImageMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
var
  ColNumb: TColor;
  R, G, B: Byte;
begin
  ColNumb := Image.Canvas.Pixels[X, Y]; {The image can't be a JPG}
  GetRGB(ColNumb, R, G, B);
  {Here are the RGB values you need}
  Label1.Caption := Format('Red: %d', [R]);
  Label2.Caption := Format('Green: %d', [G]);
  Label3.Caption := Format('Blue: %d', [B]);
end;

end.

Run the demo. Move your mouse over the image and notice the red, green and blue values being displayed in the three labels.

Demo by Peter Johnson

Original resource: The Delphi Pool
Author: Cristian Alejo Zujew
Added: 2009/09/07
Last updated: 2010/03/16