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

Asked

Viewed 1,670 times

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 notice 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 how did the need to use the stream, there goes my question: how to activate transparency when loading the image by TMemoryStream?

2 answers

1

Well, I believe that manipulating property TransparencyMode of a component TPNGImage 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, as can be seen in the following section(taken from the documentation).

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

  • Not a read only property?

  • property TransparencyMode: TPNGTransparencyMode read GetTransparencyMode; It is. This is the statement found in the documentation you posted the link to. And it indicates that it is read-only.

  • Anyway, I just tried to set it and the compiler doesn’t let it be read-only. When the documentation says "Use to determine" it is for you to know which is the current type. And not to modify.

  • @Tiagoc Do you mean Transparent?

  • It worked. But only full transparency and not semi-transparency. But I’ve found a better solution.

1


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

public
  FPNG : TPNGImage;

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

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

  Stream.Free;
end;

Delete a few lines, a fake casting unnecessary, does not generate any collateral problem and preserves the information of semi-transparent pixels.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.