I need to change the value of the alpha component when a pixel contains a specific color for a TBitmap of 32 bits, I know about the ScanLine property to access the bitmap data, but i can't figure out how change the alpha component of each pixel.
How change the alpha value of a specific color in a 32 bit TBitmap?
5k Views Asked by Salvador At
3
There are 3 best solutions below
3

For each 32 bits pixel the highest byte contains the alpha value.
var
P: Cardinal;
Alpha: Byte;
...
begin
...
P := bmp.Canvas.Pixels[x, y]; // Read Pixel
P := P and $00FFFFFF or Alpha shl 24; // combine your desired Alpha with pixel value
bmp.Canvas.Pixels[x, y] := P; // Write back
...
end;
0

I would make the following tweaks to RRUZ's answer:
procedure SetAlphaBitmap(Dest: TBitmap; Color: TColor; Alpha: Byte);
type
TRGB32 = packed record
B, G, R, A: Byte;
end;
PRGBArray32 = ^TRGBArray32;
TRGBArray32 = array[0..0] of TRGB32;
var
x, y: Integer;
Line: PRGBArray32;
ColorRGB: Longint;
Red, Green: Blue: Byte;
begin
if Dest.PixelFormat <> pf32bit then Exit;
ColorRGB := ColorToRGB(Color);
Red := GetRValue(ColorRGB);
Green := GetGValue(ColorRGB);
Blue := GetBValue(ColorRGB);
for y := 0 to Dest.Height - 1 do
begin
Line := PRGBArray32(Dest.ScanLine[y]);
for x := 0 to Dest.Width - 1 do
begin
with Line[x] do
begin
if (R = Red) and (G = Green) and (B = Blue) then
A := Alpha;
end;
end;
end;
end;
This is a basic implementation
First you need define a record to hold the ARGB structure
Then you must define a array of TRGB32 to cast the Scanline and get and set the values.
Check this sample method
Also you can take a look to this unit that i wrote to manipulate 32 bit bitmaps