Reputation: 3481
I load a png file into a TPNGImage, and then display it in a TImage. No problem. Then I create a TBitmap and assign it to the TPNGImage, and display it in a TImage. No problem.
Then I create a second TPNGImage and assign it to the TBitmap. In this case if I display it in a TImage, it has lost it's transparency. If I set the TBitmap.Transparent to True, before assigning to the PNGImage, the PNGImage is mostly transparent, but there is a small area where the transparency was lost, showing in black.
var
Bmp: TBitmap;
PngImage: TPNGImage;
PngImage2: TPNGImage;
begin
PngImage := TPNGImage.Create;
try
PngImage.LoadFromFile(FILE_NAME);
Image1.Picture.Assign(PngImage);
Bmp := TBitmap.Create;
try
Bmp.Assign(PngImage);
Image2.Picture.Assign(Bmp);
PngImage2 := TPNGImage.Create;
try
//Bmp.Transparent := True;
PngImage2.Assign(Bmp);
Image3.Picture.Assign(PngImage2);
finally
PngImage2.Free;
end;
finally
Bmp.Free;
end;
finally
PngImage.Free;
end;
end;
Result without setting Bitmap.Transparent to True:
Result when I set Bitmap.Transparent to True: There is a small bit of black in the Image
How can I assign the PNGImage to the Bitmap without losing any transparency?
Upvotes: 0
Views: 799
Reputation: 3481
I can confirm what @SertacAkyuz said in the comments. There is no problem with:
Bmp.Assign(PngImage);
The result is a 32bit image that preserves the alpha channel. The problem is with
PngImage2.Assign(Bmp);
Where the alpha is lost.
I found this library to help with the conversion:
https://github.com/graphics32/GR32PNG
Upvotes: 0
Reputation: 6502
I can only speculate... But PNGs support partial transparency, and 24-bits bitmaps don't. And since the leftover "black" pixels aren't black (they are $000101), I suspect those pixels are semi-transparent in the original png. That, or some antialising effect was applied when converting to bitmap. But I believe semi-transparency is more likely.
I never really worked with 32 bits bitmap, but maybe they could be used to preserve the transparency. (They do have an alpha channel...). But I suspect it might be more tricky than just Bitmap.Assign.
Upvotes: 1