英文:
PNG to TBitmap (preserving transparency)
问题
I use Delphi 10.3.3 VCL.
我使用 Delphi 10.3.3 VCL。
I want to load a PNG image, convert to TBitmap (in order to make some modifications), then save it as PNG.
我想加载一个 PNG 图像,将其转换为 TBitmap(以便进行一些修改),然后将其保存为 PNG。
I use this code, but it loses transparency. Transparent background becomes black.
我使用这段代码,但它丢失了透明性。透明背景变成了黑色。
var
InputPNG: TPngImage;
OutputPNG: TPngImage;
BMP: TBitmap;
begin
InputPNG := TPngImage.Create;
OutputPNG := TPngImage.Create;
BMP := TBitmap.Create;
InputPNG.LoadFromFile('C:\input.png');
BMP.Assign(InputPNG);
OutputPNG.Assign(BMP);
OutputPNG.SaveToFile('C:\output.png');
InputPNG.Free;
OutputPNG.Free;
BMP.Free;
end;
如何修改代码以保留 PNG 的透明性?
任何使用免费组件(如 Skia4Delphi)的解决方案都受欢迎。
英文:
I use Delphi 10.3.3 VCL.
I want to load a PNG image, convert to TBitmap (in order to make some modifications), then save it as PNG.
I use this code, but it loses transparency. Transparent background becomes black.
var
InputPNG: TPngImage;
OutputPNG: TPngImage;
BMP: TBitmap;
begin
InputPNG := TPngImage.Create;
OutputPNG := TPngImage.Create;
BMP := TBitmap.Create;
InputPNG.LoadFromFile('C:\input.png');
BMP.Assign(InputPNG);
OutputPNG.Assign(BMP);
OutputPNG.SaveToFile('C:\output.png');
InputPNG.Free;
OutputPNG.Free;
BMP.Free;
end;
How can I modify the code and preserve PNG transparency?
Any solutions with free components such as Skia4Delphi are welcome.
答案1
得分: 3
使用TWICImage来保存到文件。这将保留alpha通道:
procedure SaveToPng(aBmp: TBitmap; const Filename: string);
var
wic: TWICImage;
begin
Assert(aBmp.PixelFormat=pf32bit);
wic := TWICImage.Create;
try
aBmp.AlphaFormat := afDefined;
wic.Assign(aBmp);
wic.ImageFormat := wifPng;
wic.SaveToFile(Filename);
finally
wic.Free;
end;
end;
请注意,每当使用VCL.Graphics将png分配给bmp时,位图将具有Alphaformat = afDefined,这意味着RGB通道会乘以alpha。如果您现在修改位图的alpha通道,这可能会导致意外的结果。
在进行任何修改之前,我建议始终设置bmp.Alphaformat:=afIgnored。
英文:
Use a TWICImage to save to file. This will preserve the alpha-channel:
procedure SaveToPng(aBmp: TBitmap; const Filename: string);
var
wic: TWICImage;
begin
Assert(aBmp.PixelFormat=pf32bit);
wic := TWICImage.Create;
try
aBmp.AlphaFormat := afDefined;
wic.Assign(aBmp);
wic.ImageFormat := wifPng;
wic.SaveToFile(Filename);
finally
wic.Free;
end;
end;
Be aware that whenever you use VCL.Graphics to assign a png to a bmp, the bitmap will have Alphaformat = afDefined, which means the RGB-channel is multiplied by alpha. If you now modify your bitmap's alphachannel this can lead to unexpected results.
I would always set bmp.Alphaformat:=afIgnored before doing any modifications.
答案2
得分: 2
尝试在分配PNG图像之前添加这些行。
BMP.PixelFormat := pf32bit; // 不确定是否必要
BMP.Transparent := True;
BMP.Assign(iPNG);
英文:
Try to add this lines before assign the PNG image.
BMP.PixelFormat := pf32bit; // not sure if this is necessary
BMP.Transparent := True;
BMP.Assign(iPNG);
答案3
得分: 0
使用以下代码:
InputPNG.AssignTo(BMP);
英文:
Use the following code:
InputPNG.AssignTo(BMP);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论