Rectangle 27 0

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


function PngHasAlphaLayer(f: String): Boolean;
var
  fs: TFileStream;
  colorType: Byte;
begin
  fs := TFileStream.Create(f, fmOpenRead);
  fs.Position := 25;
  fs.Read(colorType, 1);
  fs.Free;
  Result := colorType and (1 shl 2) <> 0;
end;

Following function checks if a PNG file has a transparency channel. This is easy, since the main PNG header has a fixed length and the data information block IHDR must be the first occurring block.

However, this function does not check for a valid file structure for simplicity reasons. So it should be used after the PNG image has been loaded to TBitmap and then its boolean value for transparency support could be stored e. g. in the Tag property of TImage (or wherever you want).

So it is stored in the 26th byte (or 0x19 as hex), in the 3rd bit.

Note
Rectangle 27 0

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


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;

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

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):

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

You right, I don't like this solution although I had to use it, it is exactly what I want to avoid. Hence the question.

Note