Programmatically swap colors from a loaded bitmap to Red, Green, Blue or Gray, pixel by pixel.
- by eyeClaxton
Download source code here: http://www.eyeClaxton.com/download/delphi/ColorSwap.zip
I would like to take a original bitmap (light blue) and change the colors (Pixel by Pixel) to the red, green, blue and gray equivalence relation. To get an idea of what I mean, I have include the source code and a screen shot. Any help would be greatly appreciated. If more information is needed, please feel free to ask.
If you could take a look at the code below, I have three functions that I'm looking for help on. The functions "RGBToRed, RGBToGreen and RGBToRed" I can't seem to come up with the right formulas.
unit MainUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TMainFrm = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Panel2: TPanel;
Label2: TLabel;
Button1: TButton;
BeforeImage1: TImage;
AfterImage1: TImage;
RadioGroup1: TRadioGroup;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainFrm: TMainFrm;
implementation
{$R *.DFM}
function RGBToGray(RGBColor: TColor): TColor;
var
Gray: Byte;
begin
Gray := Round(
(0.90 * GetRValue(RGBColor)) +
(0.88 * GetGValue(RGBColor)) +
(0.33 * GetBValue(RGBColor)));
Result := RGB(Gray, Gray, Gray);
end;
function RGBToRed(RGBColor: TColor): TColor;
var
Red: Byte;
begin
// Not sure of the algorithm for this color
Result := RGB(Red, Red, Red);
end;
function RGBToGreen(RGBColor: TColor): TColor;
var
Green: Byte;
begin
// Not sure of the algorithm for this color
Result := RGB(Green, Green, Green);
end;
function RGBToBlue(RGBColor: TColor): TColor;
var
Blue: Byte;
begin
// Not sure of the algorithm for this color
Result := RGB(Blue, Blue, Blue);
end;
procedure TMainFrm.FormCreate(Sender: TObject);
begin
BeforeImage1.Picture.LoadFromFile('Images\RightCenter.bmp');
end;
procedure TMainFrm.Button1Click(Sender: TObject);
var
Bitmap: TBitmap;
I, X: Integer;
Color: Integer;
begin
Bitmap := TBitmap.Create;
try
Bitmap.LoadFromFile('Images\RightCenter.bmp');
for X := 0 to Bitmap.Height do
begin
for I := 0 to Bitmap.Width do
begin
Color := ColorToRGB(Bitmap.Canvas.Pixels[I, X]);
case Color of
$00000000: ; // Skip any Color Here!
else
case RadioGroup1.ItemIndex of
0: Bitmap.Canvas.Pixels[I, X] := RGBToBlue(Color);
1: Bitmap.Canvas.Pixels[I, X] := RGBToRed(Color);
2: Bitmap.Canvas.Pixels[I, X] := RGBToGreen(Color);
3: Bitmap.Canvas.Pixels[I, X] := RGBToGray(Color);
end;
end;
end;
end;
AfterImage1.Picture.Graphic := Bitmap;
finally
Bitmap.Free;
end;
end;
end.
Okay, I apologize for not making it clearer. I'm trying to take a bitmap (blue in color) and swap the blue pixels with another color. Like the shots below.