TPNGImage help

TPNGImage

Accessing thru tRNS chunk


The tRNS chunk class contains transparency information when the color type is COLOR_PALETTE (It exists also for the other color types but only for bit transparency modes). It works different than AlphaScanline property since instead of providing transparency information for each pixel in the image, it contains transparency for each palette entry.

Acessing the tRNS chunk also is really easy using the ItemFromClass method from the Chunks property. Once you have a pointer to the TChunktRNS, the transparency information for each palette entry is acessed thru the PaletteValues property, which is an array of byte. This array has a fixed size of 256 entries (0 to 255), but the valid values are between 0 and (2 POWER Header.BitDepth - 1). 255 means that the palette entry is completly opaque and 0 completly transparent.

The example bellow makes the image half transparent when the color mode is COLOR_PALETTE:

procedure MakeHalfTransparent(Obj: TPNGObject);
var
 
i: Integer;
 
TRNS: TCHUNKtRNS;
begin
 
//Creates tRNS chunk in case its not avaliable
  if
(Obj.Header.ColorType = COLOR_PALETTE)  and (Obj.Chunks.ItemFromClass(TChunktRNS) = nil) then
   
Obj.CreateAlpha();
 
//Gets pointer to the tRNS chunk
  TRNS := Obj.Chunks.ItemFromClass(TChunktRNS) as TChunktRNS;
 
//Set transparency information
  if TRNS <> nil then
    with TRNS do
      for i := 0 to DataSize - 1 do
       
PaletteValues[i] := 128
end;