Question

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.

Was it helpful?

Solution

This is a basic implementation

First you need define a record to hold the ARGB structure

  TRGB32 = record
    B, G, R, A: byte;
  end;

Then you must define a array of TRGB32 to cast the Scanline and get and set the values.

Check this sample method

procedure SetAlphaBitmap(const Dest: TBitmap;Color : TColor;Alpha:Byte);
type
  TRGB32 = record
    B, G, R, A: byte;
  end;
  PRGBArray32 = ^TRGBArray32;
  TRGBArray32 = array[0..0] of TRGB32;
var
  x, y:    integer;
  Line, Delta: integer;
  ColorRGB : TColor;
begin
  if Dest.PixelFormat<>pf32bit then  exit;

  ColorRGB:=ColorToRGB(Color);
  Line  := integer(Dest.ScanLine[0]);
  Delta := integer(Dest.ScanLine[1]) - Line;
  for y := 0 to Dest.Height - 1 do
  begin
    for x := 0 to Dest.Width - 1 do
      if TColor(RGB(PRGBArray32(Line)[x].R, PRGBArray32(Line)[x].G, PRGBArray32(Line)[x].B))=ColorRGB then
        PRGBArray32(Line)[x].A := Alpha;
    Inc(Line, Delta);
  end;
end;

Also you can take a look to this unit that i wrote to manipulate 32 bit bitmaps

OTHER TIPS

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;

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; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top