delphialpha-transparencygraphics32

Transparent Png to TBitmap32


I have a png that i would like to load in a TBitmap32.

After I load the bitmap I call:

Bitmap.DrawMode   := dmTransparent;
Bitmap.OuterColor := Bitmap.PixelS[0,0];

But then all white pixels are transparent. How can i do that just for the transparent part of the png image? Here is my image with the alpha transparency around the edge of the image indicated in the standard way.

enter image description here

And this is the actual image:

enter image description here


Solution

  • It seems that TBitmap32 may lose alpha information while loading a PNG image.

    You may consider to use the GR32PNG library of which a documentation excerpt follows:

    . . .
    since reading and writing utilizes an intermediate TBitmap object, unnecessary additional memory is required to store the bitmap data. Also by converting data to and from the TBitmap format additional information might get lost or handled wrong.
    . . .
    To handle PNG files natively by Graphics32 the thirdparty library GR32 PNG Library can be used. This library use the native PNG format as intermediate storage. By assigning a TBitmap32 object the data is encoded/decoded to/from PNG on the fly. Using this library it is also possible to access additional information, which is stored in the PNG file.

    Graphics32 project page


    The code usage example of the unit can be changed as below to suit your needs:

    var
      AlphaChannelUsed: Boolean;
    begin
      LoadBitmap32FromPNG(Bitmap, <your path to the PNG image>, AlphaChannelUsed);
    
      if AlphaChannelUsed then
        Bitmap.DrawMode := dmBlend
      else
        Bitmap.DrawMode := dmOpaque;
    end;
    

    Where Bitmap is a TBitmap32 object.


    The resulting image loaded in a form within a TImage32 component:

    enter image description here