How to load semi-transparent PNG through a memory stream?

2

I have the following structure:

public
  FBMP : TBitmap;

...
var
  PNG : TPNGImage;
  Stream : TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  Stream.LoadFromFile('foo.png');

  PNG := TPNGImage.Create;
  PNG.LoadFromStream(Stream);

  FBMP := TBitmap.Create;
  FBMP.Assign(PNG);

  PNG.Free;
  Stream.Free;
end;

When I try to draw the image above, I realize that it does not recognize the semi-transparency of the PNG file (showing all opaque colors), a phenomenon that did not happen when I did not use the stream . But as the need arose to use the stream , there goes my question: how to enable transparency when loading the image by TMemoryStream ?

    
asked by anonymous 28.03.2014 / 04:40

2 answers

1

I realized that it is very "gambiarroso" what I am doing. The best practice would be to use only TPNGImage , like this:

public
  FPNG : TPNGImage;

...
var
  Stream : TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  Stream.LoadFromFile('foo.png');

  FPNG := TPNGImage.Create;
  FPNG.LoadFromStream(Stream);

  Stream.Free;
end;

It eliminates some lines, an unnecessary false casting, does not cause any collateral problem and preserves the information of semi-transparent pixels.

    
28.03.2014 / 06:12
1

Well, I believe manipulating the TransparencyMode property of a TPNGImage component should be useful to you.

Uses pngimage;
// ...   
var
  PNG : TPNGImage;
// ...
begin
  // ...
  PNG := TPNGImage.Create;
  PNG.LoadFromStream(Stream);
  PNG.TransparencyMode := ptmBit;
  // ...

This property is not read-only, but can be seen in the following excerpt ( removed from the documentation ).

  

Use TransparencyMode to determine the mode of transparency of the image   png uses ....

    
28.03.2014 / 05:29