简体   繁体   English

Delphi,将一个PNG图片的内容复制到另一个不同大小的PNG图片

[英]Delphi, copy content of a PNG image to another PNG image of different size

I want to copy the content of a PNG image to another bigger one.我想将 PNG 图像的内容复制到另一个更大的图像。 Source image is 16x16x32b, the destination is of the same format but two times broader.源图像是 16x16x32b,目标是相同的格式,但宽两倍。 However the code below produces empty image.但是下面的代码产生空图像。 Changing COLOR_RGBALPHA to COLOR_RGB produces non transparent PNG.将 COLOR_RGBALPHA 更改为 COLOR_RGB 会生成不透明的 PNG。 How to make it properly?如何正确制作?

var
  png, pngsrc: TPngImage;
begin
  png := TPngImage.CreateBlank(COLOR_RGBALPHA, 8, 32, 16);
  pngsrc := TPngImage.Create;
  try
    pngsrc.LoadFromFile('c:\src.png');
    pngsrc.Draw(png.Canvas, Rect(16, 0, 32, 16));
    png.SaveToFile('c:\dst.png');
  finally
    png.Free;
    pngsrc.Free;
  end;

Copying a PNG with transparency into a larger PNG image can be achieved by transferring the alpha data as a separate step, as per the following code.将具有透明度的 PNG 复制到更大的 PNG 图像可以通过将 alpha 数据作为单独的步骤传输来实现,如以下代码所示。

var
  png, pngsrc: TPngImage;
  X: Integer;
  Y: Integer;
  XOffset: Integer;
  YOffset: Integer;
  srcAlphaArray: pByteArray;
  destAlphaArray: pByteArray;
begin
  // Inspired by https://www.bverhue.nl/delphisvg/2016/09/26/save-bitmap-with-transparency-as-png-in-vcl/
  // Optional X and Y offsets to position source png into destination png
  XOffset := 16;
  YOffset := 0;
  png := TPngImage.CreateBlank(COLOR_RGBALPHA, 8, 32, 16);
  png.CreateAlpha;
  png.Canvas.CopyMode := cmSrcCopy;
  pngsrc := TPngImage.Create;
  try
    pngsrc.LoadFromFile('c:\src.png');
    pngsrc.Draw(png.Canvas, Rect(XOffset, YOffset, pngsrc.Width + XOffset, pngsrc.Height + YOffset));

    if pngsrc.TransparencyMode = ptmPartial then
    begin
      // Update destination png with tranparency data from original
      for Y := 0 to Pred(pngsrc.Height) do
      begin
        srcAlphaArray := pngsrc.AlphaScanline[Y];
        destAlphaArray := png.AlphaScanline[Y + YOffset];
        for X := 0 to Pred(pngsrc.Width) do
        begin
          destAlphaArray^[X + XOffset] := srcAlphaArray^[X];
        end;
      end;
    end;

    png.SaveToFile('c:\dst.png');
  finally
    png.Free;
    pngsrc.Free;
  end;
end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM