delphipngdelphi-xe2firemonkeytbitmap

How to check if the PNG image loaded into FMX.TBitmap has an alpha channel?


I'm loading PNG images into FMX.Type.TBitmap in Delphi-XE2 Update3 FireMonkey HD application. How do I check if loaded PNG image has an alpha channel or not?

Currently if I load an image with an alpha channel it has alpha info in Bitmap.Scanline[Y]^[X] in a form of $AABBGGRR. However if I load PNG image without alpha the said record has only $00BBGGRR entries (AA = 0), just like an image with clear alpha. Hence the problem - how to determine if it is RGBA image with the alpha fully transparent or it is a RGB image (in this case I will process it to make the alpha fully opaque). Note: Checking through all pixels is not an option.

FMX TBitmap has no PixelFormat property, nor I could find HasAlpha flag.


Solution

  • You're probably not going to like this.

    All bitmaps in FMX are 32-bit, and they are loaded and saved using code from the OS, which is all 32-bit.

    So, the real answer is that all bitmaps have an alpha channel.

    But, what you really want to know is whether the bitmap uses the alpha channel, and the only way to tell this would be to iterate over every pixel and see if any have an alpha channel which is <> 255.

    I would recommmend something like the following (untested):

    function TBitmap.IsAlpha(Bitmap: TBitmap): Boolean;
    var
      I, j: Integer;
      Bits: PAlphaColorRecArray;
    begin
      Bits := PAlphaColorRecArray(StartLine);
      for j := 0 to Height - 1 do
        for I := 0 to Width - 1 do
        begin
          if Bits[I + (j * Width)].A <> 255 then
          begin
            Result := True;
            EXIT;
          end;
        end;
      Result := False;
    end;