{unit to write tbitmaps to a png using plugwashes png code}

{ Copyright (C) 2008 Peter Green
  For conditions of distribution and use, see copyright notice in zlib_license.txt
  which is included in the package
      ----------------------------------------------------------------------------- }
      

unit pngwritetbitmap;

interface
uses
  pngwrite,
  sysutils,
  classes,
  {$ifdef win32}
    windows,
  {$endif}
  {$ifndef fpc}

    Graphics;

  {$else}
    pgtbitmap;
  {$endif}
  
procedure savetbitmaptopng(image:tbitmap;destination : tstream);
implementation
procedure savetbitmaptopng(image:tbitmap;destination : tstream);
var
  paletteentrieswin : array[0..255] of TPaletteEntry;
  paletteentriespng : array[0..768] of byte;
  f:tpngwrite;
  i : integer;
  colortype : tcolortype;
begin
  if (image.PixelFormat <> pf8bit) and (image.pixelformat <> pf24bit) then raise exception.create('unsupported image format, only 8 bit and 24 bit per pixel are currently supported.');
  if image.PixelFormat = pf24bit then begin
    colortype := ctbgr;
  end else begin
    colortype := ctpallette;
  end;
  pngstart(f,destination,8,colortype,image.Height,image.Width);

  if image.pixelformat = pf8bit then begin
    GetPaletteEntries(image.Palette,0,256,paletteEntrieswin);

    //writeln('about to start png write');
    //writeln('about to prepare pallette');
    for i := 0 to 255 do begin
      paletteentriespng[(i*3)  ] := paletteEntrieswin[i].pered;
      paletteentriespng[(i*3)+1] := paletteEntrieswin[i].pegreen;
      paletteentriespng[(i*3)+2] := paletteEntrieswin[i].peblue;
    end;
    //writeln('about to write pallette');
    pngwritepal(f,@paletteentriespng,256 );
  end;

  pngstartdata(f);
  {$O-}
  for i := 0 to Image.Height -1 do begin;
    //writeln('about to write scanline ',i,'image.height=',image.height,'image.ScanLine[i]',longint(image.ScanLine[i]));
    pngwritescanline(f,image.ScanLine[i]);
  end;
  //writeln('about to close main data block');
  pngfinishdata(f);
  //writeln('about to close png');
  pngfinish(f);

end;
end.
