How to copy one PNG from other PNG?

后端 未结 3 1285
旧时难觅i
旧时难觅i 2021-02-03 10:58

My application needs a lot of PNGs and I often mess up my code while trying to work with them. To make my life easier I made one big PNG image in Realword Paint and pasted all t

3条回答
  •  一生所求
    2021-02-03 11:57

    Here is another version (It works very fast):

    procedure CropPNG(Source: TPNGObject; Left, Top, Width, Height: Integer;
      out Target: TPNGObject);
    var
      IsAlpha: Boolean;
      Line: Integer;
    begin
      if (Source.Width < (Left + Width)) or (Source.Height < (Top + Height)) then
        raise Exception.Create('Invalid position/size');
    
      Target := TPNGObject.CreateBlank(Source.Header.ColorType, 
        Source.Header.BitDepth, Width, Height);
      IsAlpha := Source.Header.ColorType in [COLOR_GRAYSCALEALPHA, COLOR_RGBALPHA];
      for Line := 0 to Target.Height - 1 do
      begin
        if IsAlpha then
          CopyMemory(Target.AlphaScanline[Line], 
            Ptr(LongInt(Source.AlphaScanline[Line + Top]) + LongInt(Left)), 
            Target.Width);
        CopyMemory(Target.Scanline[Line], 
          Ptr(LongInt(Source.Scanline[Line + Top]) + LongInt(Left * 3)), 
          Target.Width * 3);
      end;
    end;
    

    Note: The above code is compatible with the newer pngimage Version 1.56+ (which supports the CreateBlank constructor)

提交回复
热议问题