delphibitmaptbitmap

How change the alpha value of a specific color in a 32 bit TBitmap?


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.


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