본문 바로가기

프로그래밍/Delphi

GR32에서 투명한 PNG파일 버퍼로 읽어오기

procedure LoadBitmap32FromPNG(fname: string; bm32: TBitmap32);
var
  png: TPngObject;
  tc: TColor32;
  x, y: Integer;
  bm: TBitmap;
  p: pngimage.PByteArray;
begin
  bm := nil;
  png := nil;
  try
    png := TPngObject.Create;
    png.LoadFromFile(fname);
    bm := TBitmap.Create;
    bm.Assign(png);
    bm32.Assign(bm);
    bm32.ResetAlpha;
    case png.TransparencyMode of
      ptmBit: begin
          tc := Color32(png.TransparentColor);
          for y := 0 to bm32.Height - 1 do
            for x := 0 to bm32.Width - 1 do
              if bm32.Pixel[x, y] = tc then PRGBQuad(bm32.PixelPtr[x, y])^.rgbReserved := 0;
        end;
      ptmPartial: begin
          if (png.Header.ColorType = COLOR_GRAYSCALEALPHA) or
            (png.Header.ColorType = COLOR_RGBALPHA) then begin
            for y := 0 to bm32.Height - 1 do begin
              p := png.AlphaScanline[y];
              for x := 0 to bm32.Width - 1 do
                PRGBQuad(bm32.PixelPtr[x, y])^.rgbReserved := p[x];
            end;
          end;
        end;
    end;
  finally
    if Assigned(bm) then bm.Free;
    if Assigned(png) then png.Free;
  end
end;