{
    "mode": "man",
    "parameter": "libpng",
    "section": "3",
    "url": "https://www.chedong.com/phpMan.php/man/libpng/3/json",
    "generated": "2026-10-04T21:18:07Z",
    "synopsis": "",
    "sections": {
        "NAME": {
            "content": "libpng - Portable Network Graphics (PNG) Reference Library 1.6.43\n\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "",
            "subsections": [
                {
                    "name": "#include <png.h>",
                    "content": ""
                },
                {
                    "name": "png_uint_32 png_access_version_number (void);",
                    "content": "void pngbenignerror (pngstructp pngptr, pngconstcharp error);\n\nvoid pngbuildgrayscalepalette (int bitdepth, pngcolorp palette);\n\npngvoidp pngcalloc (pngstructp pngptr, pngallocsizet size);\n\nvoid pngchunkbenignerror (pngstructp pngptr, pngconstcharp error);\n\nvoid pngchunkerror (pngstructp pngptr, pngconstcharp error);\n\nvoid pngchunkwarning (pngstructp pngptr, pngconstcharp message);\n\nvoid pngconvertfromstructtm (pngtimep ptime, struct tm FAR * ttime);\n\nvoid pngconvertfromtimet (pngtimep ptime, timet ttime);\n\npngcharp pngconverttorfc1123 (pngstructp pngptr, pngtimep ptime);\n\npnginfop pngcreateinfostruct (pngstructp pngptr);\n\npngstructp   pngcreatereadstruct   (pngconstcharp  userpngver,  pngvoidp  errorptr,\npngerrorptr errorfn, pngerrorptr warnfn);\n\npngstructp  pngcreatereadstruct2  (pngconstcharp  userpngver,  pngvoidp  errorptr,\npngerrorptr  errorfn,  pngerrorptr warnfn, pngvoidp memptr, pngmallocptr mallocfn,\npngfreeptr freefn);\n\npngstructp  pngcreatewritestruct  (pngconstcharp  userpngver,  pngvoidp   errorptr,\npngerrorptr errorfn, pngerrorptr warnfn);\n\npngstructp  pngcreatewritestruct2  (pngconstcharp  userpngver,  pngvoidp errorptr,\npngerrorptr errorfn, pngerrorptr warnfn, pngvoidp memptr,  pngmallocptr  mallocfn,\npngfreeptr freefn);\n\nvoid pngdatafreer (pngstructp pngptr, pnginfop infoptr, int freer, pnguint32 mask);\n\nvoid pngdestroyinfostruct (pngstructp pngptr, pnginfopp infoptrptr);\n\nvoid  pngdestroyreadstruct  (pngstructpp pngptrptr, pnginfopp infoptrptr, pnginfopp\nendinfoptrptr);\n\nvoid pngdestroywritestruct (pngstructpp pngptrptr, pnginfopp infoptrptr);\n\nvoid pngerr (pngstructp pngptr);\n\nvoid pngerror (pngstructp pngptr, pngconstcharp error);\n\nvoid pngfree (pngstructp pngptr, pngvoidp ptr);\n\nvoid pngfreechunklist (pngstructp pngptr);\n\nvoid pngfreedefault (pngstructp pngptr, pngvoidp ptr);\n\nvoid pngfreedata (pngstructp pngptr, pnginfop infoptr, int num);\n\npngbyte pnggetbitdepth (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetbKGD (pngconststructp pngptr, pnginfop infoptr, pngcolor16p *back‐\nground);\n\npngbyte pnggetchannels (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32  pnggetcHRM  (pngconststructp  pngptr,  pngconstinfop   infoptr,   double\n*whitex,  double  *whitey,  double *redx, double *redy, double *greenx, double *greeny,\ndouble *bluex, double *bluey);\n\npnguint32  pnggetcHRMfixed   (pngconststructp   pngptr,   pngconstinfop   infoptr,\npnguint32   *whitex,   pnguint32   *whitey,  pnguint32  *redx,  pnguint32  *redy,\npnguint32 *greenx, pnguint32 *greeny, pnguint32 *bluex, pnguint32 *bluey);\n\npnguint32 pnggetcHRMXYZ (pngstructp pngptr, pngconstinfop infoptr,  double  *redX,\ndouble  *redY,  double  *redZ,  double  *greenX,  double *greenY, double *greenZ, double\n*blueX, double *blueY, double *blueZ);\n\npnguint32   pnggetcHRMXYZfixed   (pngstructp   pngptr,   pngconstinfop    infoptr,\npngfixedpoint   *intredX,   pngfixedpoint   *intredY,   pngfixedpoint   *intredZ,\npngfixedpoint *intgreenX,  pngfixedpoint  *intgreenY,  pngfixedpoint  *intgreenZ,\npngfixedpoint *intblueX, pngfixedpoint *intblueY, pngfixedpoint *intblueZ);\n\npnguint32 pnggetchunkcachemax (pngconststructp pngptr);\n\npngallocsizet pnggetchunkmallocmax (pngconststructp pngptr);\n\npngbyte pnggetcolortype (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetcompressionbuffersize (pngconststructp pngptr);\n\npngbyte pnggetcompressiontype (pngconststructp pngptr, pngconstinfop infoptr);\n\npngbyte pnggetcopyright (pngconststructp pngptr);\n\npnguint32 pnggetcurrentrownumber (pngconststructp);\n\npngbyte pnggetcurrentpassnumber (pngconststructp);\n\npngvoidp pnggeterrorptr (pngconststructp pngptr);\n\npngbyte pnggetfiltertype (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32   pnggetgAMA   (pngconststructp  pngptr,  pngconstinfop  infoptr,  double\n*filegamma);\n\npnguint32  pnggetgAMAfixed   (pngconststructp   pngptr,   pngconstinfop   infoptr,\npnguint32 *intfilegamma);\n\npngbyte pnggetheaderver (pngconststructp pngptr);\n\npngbyte pnggetheaderversion (pngconststructp pngptr);\n\npnguint32  pnggeteXIf  (pngconststructp  pngptr,  pngconstinfop  infoptr, pngbytep\n*exif);\n\npnguint32 pnggeteXIf1 (pngconststructp pngptr, pngconstinfop infoptr,  pngunit32\n*numexif, pngbytep *exif);\n\npnguint32  pnggethIST  (pngconststructp pngptr, pngconstinfop infoptr, pnguint16p\n*hist);\n\npnguint32 pnggetiCCP (pngconststructp  pngptr,  pngconstinfop  infoptr,  pngcharpp\nname, int *compressiontype, pngbytepp profile, pnguint32 *proflen);\n\npnguint32  pnggetIHDR  (pngstructp  pngptr,  pnginfop  infoptr,  pnguint32  *width,\npnguint32 *height, int *bitdepth, int  *colortype,  int  *interlacetype,  int  *compres‐\nsiontype, int *filtertype);\n\npnguint32 pnggetimageheight (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetimagewidth (pngconststructp pngptr, pngconstinfop infoptr);\n\npngint32 pnggetint32 (pngbytep buf);\n\npngbyte pnggetinterlacetype (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetiochunktype (pngconststructp pngptr);\n\npngvoidp pnggetioptr (pngstructp pngptr);\n\npnguint32 pnggetiostate (pngstructp pngptr);\n\npngbyte pnggetlibpngver (pngconststructp pngptr);\n\nint pnggetpalettemax(pngconststructp pngptr, pngconstinfop infoptr);\n\npngvoidp pnggetmemptr (pngconststructp pngptr);\n\npnguint32  pnggetoFFs  (pngconststructp  pngptr, pngconstinfop infoptr, pnguint32\n*offsetx, pnguint32 *offsety, int *unittype);\n\npnguint32 pnggetpCAL  (pngconststructp  pngptr,  pngconstinfop  infoptr,  pngcharp\n*purpose,  pngint32  *X0,  pngint32  *X1,  int  *type,  int  *nparams,  pngcharp *units,\npngcharpp *params);\n\npnguint32 pnggetpHYs (pngconststructp pngptr,  pngconstinfop  infoptr,  pnguint32\n*resx, pnguint32 *resy, int *unittype);\n\nfloat pnggetpixelaspectratio (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32    pnggetpHYsdpi   (pngconststructp   pngptr,   pngconstinfop   infoptr,\npnguint32 *resx, pnguint32 *resy, int *unittype);\n\npngfixedpoint pnggetpixelaspectratiofixed (pngconststructp pngptr,  pngconstinfop\ninfoptr);\n\npnguint32 pnggetpixelsperinch (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetpixelspermeter (pngconststructp pngptr, pngconstinfop infoptr);\n\npngvoidp pnggetprogressiveptr (pngconststructp pngptr);\n\npnguint32  pnggetPLTE  (pngconststructp  pngptr,  pngconstinfop infoptr, pngcolorp\n*palette, int *numpalette);\n\npngbyte pnggetrgbtograystatus (pngconststructp pngptr);\n\npnguint32 pnggetrowbytes (pngconststructp pngptr, pngconstinfop infoptr);\n\npngbytepp pnggetrows (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32  pnggetsBIT  (pngconststructp  pngptr,  pnginfop   infoptr,   pngcolor8p\n*sigbit);\n\nvoid  pnggetsCAL  (pngconststructp  pngptr, pngconstinfop infoptr, int* unit, double*\nwidth, double* height);\n\nvoid pnggetsCALfixed (pngconststructp  pngptr,  pngconstinfop  infoptr,  int*  unit,\npngfixedpointp width, pngfixedpointp height);\n\nvoid   pnggetsCALs   (pngconststructp  pngptr,  pngconstinfop  infoptr,  int*  unit,\npngcharpp width, pngcharpp height);\n\npngbytep pnggetsignature (pngconststructp pngptr, pnginfop infoptr);\n\npnguint32 pnggetsPLT (pngconststructp pngptr, pngconstinfop infoptr, pngspalettep\n*spltptr);\n\npnguint32  pnggetsRGB   (pngconststructp   pngptr,   pngconstinfop   infoptr,   int\n*filesrgbintent);\n\npnguint32  pnggettext  (pngconststructp  pngptr,  pngconstinfop  infoptr, pngtextp\n*textptr, int *numtext);\n\npnguint32  pnggettIME   (pngconststructp   pngptr,   pnginfop   infoptr,   pngtimep\n*modtime);\n\npnguint32 pnggettRNS (pngconststructp pngptr, pnginfop infoptr, pngbytep *transal‐\npha, int *numtrans, pngcolor16p *transcolor);\n\n/* This function is really an inline macro. */\n\npnguint16 pnggetuint16 (pngbytep buf);\n\npnguint32 pnggetuint31 (pngstructp pngptr, pngbytep buf);\n\n/* This function is really an inline macro. */\n\npnguint32 pnggetuint32 (pngbytep buf);\n\npnguint32  pnggetunknownchunks  (pngconststructp  pngptr,  pngconstinfop  infoptr,\npngunknownchunkpp unknowns);\n\npngvoidp pnggetuserchunkptr (pngconststructp pngptr);\n\npnguint32 pnggetuserheightmax (pngconststructp pngptr);\n\npngvoidp pnggetusertransformptr (pngconststructp pngptr);\n\npnguint32 pnggetuserwidthmax (pngconststructp pngptr);\n\npnguint32 pnggetvalid (pngconststructp pngptr, pngconstinfop  infoptr,  pnguint32\nflag);\n\nfloat pnggetxoffsetinches (pngconststructp pngptr, pngconstinfop infoptr);\n\npngfixedpoint    pnggetxoffsetinchesfixed    (pngstructp   pngptr,   pngconstinfop\ninfoptr);\n\npngint32 pnggetxoffsetmicrons (pngconststructp pngptr, pngconstinfop infoptr);\n\npngint32 pnggetxoffsetpixels (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetxpixelsperinch (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetxpixelspermeter (pngconststructp pngptr, pngconstinfop infoptr);\n\nfloat pnggetyoffsetinches (pngconststructp pngptr, pngconstinfop infoptr);\n\npngfixedpoint   pnggetyoffsetinchesfixed   (pngstructp    pngptr,    pngconstinfop\ninfoptr);\n\npngint32 pnggetyoffsetmicrons (pngconststructp pngptr, pngconstinfop infoptr);\n\npngint32 pnggetyoffsetpixels (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetypixelsperinch (pngconststructp pngptr, pngconstinfop infoptr);\n\npnguint32 pnggetypixelspermeter (pngconststructp pngptr, pngconstinfop infoptr);\n\nint pnghandleasunknown (pngstructp pngptr, pngbytep chunkname);\n\nint pngimagebeginreadfromfile (pngimagep image, const char *filename);\n\nint pngimagebeginreadfromstdio (pngimagep image, FILE* file);\n\nint,  pngimagebeginreadfrommemory  (pngimagep  image,  pngconstvoidp  memory,  sizet\nsize);\n\nint pngimagefinishread (pngimagep image, pngcolorp background, void *buffer,  pngint32\nrowstride, void *colormap);\n\nvoid pngimagefree (pngimagep image);\n\nint  pngimagewritetofile  (pngimagep image, const char *file, int convertto8bit, const\nvoid *buffer, pngint32 rowstride, void *colormap);\n\nint pngimagewritetomemory (pngimagep image, void  *memory,  pngallocsizet  *  PNGRE‐\nSTRICT  memorybytes,  int convertto8bit, const void *buffer, pngint32 rowstride, const\nvoid *colormap);\n\nint pngimagewritetostdio (pngimagep image, FILE *file, int convertto8bit, const  void\n*buffer, pngint32 rowstride, void *colormap);\n\nvoid pnginfoinit3 (pnginfopp infoptr, sizet pnginfostructsize);\n\nvoid pnginitio (pngstructp pngptr, FILE *fp);\n\nvoid pnglongjmp (pngstructp pngptr, int val);\n\npngvoidp pngmalloc (pngstructp pngptr, pngallocsizet size);\n\npngvoidp pngmallocdefault (pngstructp pngptr, pngallocsizet size);\n\npngvoidp pngmallocwarn (pngstructp pngptr, pngallocsizet size);\n\npnguint32  pngpermitmngfeatures  (pngstructp  pngptr, pnguint32 mngfeaturespermit‐\nted);\n\nvoid pngprocessdata (pngstructp pngptr,  pnginfop  infoptr,  pngbytep  buffer,  sizet\nbuffersize);\n\nsizet pngprocessdatapause (pngstructp pngptr, int save);\n\npnguint32 pngprocessdataskip (pngstructp pngptr);\n\nvoid pngprogressivecombinerow (pngstructp pngptr, pngbytep oldrow, pngbytep newrow);\n\nvoid pngreadend (pngstructp pngptr, pnginfop infoptr);\n\nvoid pngreadimage (pngstructp pngptr, pngbytepp image);\n\nvoid pngreadinfo (pngstructp pngptr, pnginfop infoptr);\n\nvoid  pngreadpng  (pngstructp  pngptr,  pnginfop  infoptr,  int  transforms,  pngvoidp\nparams);\n\nvoid pngreadrow (pngstructp pngptr, pngbytep row, pngbytep displayrow);\n\nvoid pngreadrows (pngstructp pngptr, pngbytepp row, pngbytepp displayrow,  pnguint32\nnumrows);\n\nvoid pngreadupdateinfo (pngstructp pngptr, pnginfop infoptr);\n\nint pngresetzstream (pngstructp pngptr);\n\nvoid pngsaveint32 (pngbytep buf, pngint32 i);\n\nvoid pngsaveuint16 (pngbytep buf, unsigned int i);\n\nvoid pngsaveuint32 (pngbytep buf, pnguint32 i);\n\nvoid pngsetaddalpha (pngstructp pngptr, pnguint32 filler, int flags);\n\nvoid pngsetalphamode (pngstructp pngptr, int mode, double outputgamma);\n\nvoid pngsetalphamodefixed (pngstructp pngptr, int mode, pngfixedpoint outputgamma);\n\nvoid  pngsetbackground  (pngstructp  pngptr,  pngcolor16p  backgroundcolor,  int back‐\ngroundgammacode, int needexpand, double backgroundgamma);\n\nvoid pngsetbackgroundfixed (pngstructp pngptr, pngcolor16p backgroundcolor, int back‐\ngroundgammacode, int needexpand, pnguint32 backgroundgamma);\n\nvoid pngsetbenignerrors (pngstructp pngptr, int allowed);\n\nvoid pngsetbgr (pngstructp pngptr);\n\nvoid pngsetbKGD (pngstructp pngptr, pnginfop infoptr, pngcolor16p background);\n\nvoid pngsetcheckforinvalidindex (pngstructrp pngptr, int allowed);\n\nvoid pngsetcHRM (pngstructp pngptr, pnginfop infoptr, double whitex,  double  whitey,\ndouble redx, double redy, double greenx, double greeny, double bluex, double bluey);\n\nvoid  pngsetcHRMfixed  (pngstructp  pngptr,  pnginfop  infoptr,  pnguint32  whitex,\npnguint32 whitey, pnguint32 redx, pnguint32 redy, pnguint32  greenx,  pnguint32\ngreeny, pnguint32 bluex, pnguint32 bluey);\n\nvoid  pngsetcHRMXYZ  (pngstructp pngptr, pnginfop infoptr, double redX, double redY,\ndouble redZ, double greenX, double greenY, double greenZ, double blueX,  double  blueY,\ndouble blueZ);\n\nvoid   pngsetcHRMXYZfixed   (pngstructp  pngptr,  pnginfop  infoptr,  pngfixedpoint\nintredX, pngfixedpoint intredY, pngfixedpoint intredZ, pngfixedpoint intgreenX,\npngfixedpoint  intgreenY,  pngfixedpoint   intgreenZ,   pngfixedpoint   intblueX,\npngfixedpoint intblueY, pngfixedpoint intblueZ);\n\nvoid pngsetchunkcachemax (pngstructp pngptr, pnguint32 userchunkcachemax);\n\nvoid pngsetcompressionlevel (pngstructp pngptr, int level);\n\nvoid pngsetcompressionmemlevel (pngstructp pngptr, int memlevel);\n\nvoid pngsetcompressionmethod (pngstructp pngptr, int method);\n\nvoid pngsetcompressionstrategy (pngstructp pngptr, int strategy);\n\nvoid pngsetcompressionwindowbits (pngstructp pngptr, int windowbits);\n\nvoid pngsetcrcaction (pngstructp pngptr, int critaction, int ancilaction);\n\nvoid  pngseterrorfn  (pngstructp  pngptr,  pngvoidp  errorptr, pngerrorptr errorfn,\npngerrorptr warningfn);\n\nvoid pngsetexpand (pngstructp pngptr);\n\nvoid pngsetexpand16 (pngstructp pngptr);\n\nvoid pngsetexpandgray124to8 (pngstructp pngptr);\n\nvoid pngsetfiller (pngstructp pngptr, pnguint32 filler, int flags);\n\nvoid pngsetfilter (pngstructp pngptr, int method, int filters);\n\nvoid pngsetfilterheuristics (pngstructp pngptr, int heuristicmethod,  int  numweights,\npngdoublep filterweights, pngdoublep filtercosts);\n\nvoid   pngsetfilterheuristicsfixed   (pngstructp   pngptr,  int  heuristicmethod,  int\nnumweights, pngfixedpointp filterweights, pngfixedpointp filtercosts);\n\nvoid pngsetflush (pngstructp pngptr, int nrows);\n\nvoid pngsetgamma (pngstructp pngptr, double screengamma, double defaultfilegamma);\n\nvoid pngsetgammafixed (pngstructp  pngptr,  pnguint32  screengamma,  pnguint32  de‐\nfaultfilegamma);\n\nvoid pngsetgAMA (pngstructp pngptr, pnginfop infoptr, double filegamma);\n\nvoid pngsetgAMAfixed (pngstructp pngptr, pnginfop infoptr, pnguint32 filegamma);\n\nvoid pngsetgray124to8 (pngstructp pngptr);\n\nvoid pngsetgraytorgb (pngstructp pngptr);\n\nvoid pngseteXIf (pngstructp pngptr, pnginfop infoptr, pngbytep exif);\n\nvoid pngseteXIf1 (pngstructp pngptr, pnginfop infoptr, pnguint32 numexif, pngbytep\nexif);\n\nvoid pngsethIST (pngstructp pngptr, pnginfop infoptr, pnguint16p hist);\n\nvoid  pngsetiCCP  (pngstructp  pngptr, pnginfop infoptr, pngconstcharp name, int com‐\npressiontype, pngconstbytep profile, pnguint32 proflen);\n\nint pngsetinterlacehandling (pngstructp pngptr);\n\nvoid pngsetinvalid (pngstructp pngptr, pnginfop infoptr, int mask);\n\nvoid pngsetinvertalpha (pngstructp pngptr);\n\nvoid pngsetinvertmono (pngstructp pngptr);\n\nvoid pngsetIHDR (pngstructp pngptr, pnginfop infoptr,  pnguint32  width,  pnguint32\nheight,  int  bitdepth,  int  colortype, int interlacetype, int compressiontype, int fil‐\ntertype);\n\nvoid pngsetkeepunknownchunks (pngstructp pngptr, int keep,  pngbytep  chunklist,  int\nnumchunks);\n\njmpbuf*   pngsetlongjmpfn   (pngstructp   pngptr,  pnglongjmpptr  longjmpfn,  sizet\njmpbufsize);\n\nvoid pngsetchunkmallocmax (pngstructp pngptr, pngallocsizet userchunkcachemax);\n\nvoid pngsetcompressionbuffersize (pngstructp pngptr, pnguint32 size);\n\nvoid  pngsetmemfn  (pngstructp  pngptr,  pngvoidp  memptr,  pngmallocptr  mallocfn,\npngfreeptr freefn);\n\nvoid pngsetoFFs (pngstructp pngptr, pnginfop infoptr, pnguint32 offsetx, pnguint32\noffsety, int unittype);\n\nint pngsetoption(pngstructrp pngptr, int option, int onoff);\n\nvoid pngsetpacking (pngstructp pngptr);\n\nvoid pngsetpackswap (pngstructp pngptr);\n\nvoid pngsetpalettetorgb (pngstructp pngptr);\n\nvoid pngsetpCAL (pngstructp pngptr, pnginfop infoptr, pngcharp purpose, pngint32 X0,\npngint32 X1, int type, int nparams, pngcharp units, pngcharpp params);\n\nvoid  pngsetpHYs  (pngstructp  pngptr, pnginfop infoptr, pnguint32 resx, pnguint32\nresy, int unittype);\n\nvoid pngsetprogressivereadfn (pngstructp pngptr,  pngvoidp  progressiveptr,  pngpro‐\ngressiveinfoptr infofn, pngprogressiverowptr rowfn, pngprogressiveendptr endfn);\n\nvoid   pngsetPLTE   (pngstructp  pngptr,  pnginfop  infoptr,  pngcolorp  palette,  int\nnumpalette);\n\nvoid pngsetquantize (pngstructp pngptr, pngcolorp palette, int  numpalette,  int  maxi‐\nmumcolors, pnguint16p histogram, int fullquantize);\n\nvoid pngsetreadfn (pngstructp pngptr, pngvoidp ioptr, pngrwptr readdatafn);\n\nvoid pngsetreadstatusfn (pngstructp pngptr, pngreadstatusptr readrowfn);\n\nvoid    pngsetreaduserchunkfn    (pngstructp    pngptr,    pngvoidp   userchunkptr,\npnguserchunkptr readuserchunkfn);\n\nvoid    pngsetreadusertransformfn    (pngstructp    pngptr,     pngusertransformptr\nreadusertransformfn);\n\nvoid pngsetrgbtogray (pngstructp pngptr, int erroraction, double red, double green);\n\nvoid  pngsetrgbtograyfixed  (pngstructp  pngptr,  int  erroraction  pnguint32  red,\npnguint32 green);\n\nvoid pngsetrows (pngstructp pngptr, pnginfop infoptr, pngbytepp rowpointers);\n\nvoid pngsetsBIT (pngstructp pngptr, pnginfop infoptr, pngcolor8p sigbit);\n\nvoid pngsetsCAL (pngstructp pngptr, pnginfop infoptr, int unit,  double  width,  double\nheight);\n\nvoid  pngsetsCALfixed  (pngstructp pngptr, pnginfop infoptr, int unit, pngfixedpoint\nwidth, pngfixedpoint height);\n\nvoid pngsetsCALs (pngstructp pngptr, pnginfop  infoptr,  int  unit,  pngcharp  width,\npngcharp height);\n\nvoid pngsetscale16 (pngstructp pngptr);\n\nvoid pngsetshift (pngstructp pngptr, pngcolor8p truebits);\n\nvoid pngsetsigbytes (pngstructp pngptr, int numbytes);\n\nvoid  pngsetsPLT  (pngstructp  pngptr,  pnginfop  infoptr, pngspalettep spltptr, int\nnumspalettes);\n\nvoid pngsetsRGB (pngstructp pngptr, pnginfop infoptr, int srgbintent);\n\nvoid pngsetsRGBgAMAandcHRM (pngstructp pngptr, pnginfop infoptr, int srgbintent);\n\nvoid pngsetstrip16 (pngstructp pngptr);\n\nvoid pngsetstripalpha (pngstructp pngptr);\n\nvoid pngsetstriperrornumbers (pngstructp pngptr, pnguint32 stripmode);\n\nvoid pngsetswap (pngstructp pngptr);\n\nvoid pngsetswapalpha (pngstructp pngptr);\n\nvoid  pngsettext  (pngstructp  pngptr,  pnginfop  infoptr,  pngtextp   textptr,   int\nnumtext);\n\nvoid pngsettextcompressionlevel (pngstructp pngptr, int level);\n\nvoid pngsettextcompressionmemlevel (pngstructp pngptr, int memlevel);\n\nvoid pngsettextcompressionstrategy (pngstructp pngptr, int strategy);\n\nvoid pngsettextcompressionwindowbits (pngstructp pngptr, int windowbits);\n\nvoid pngsettextcompressionmethod (pngstructp pngptr, int method);\n\nvoid pngsettIME (pngstructp pngptr, pnginfop infoptr, pngtimep modtime);\n\nvoid  pngsettRNS  (pngstructp  pngptr,  pnginfop  infoptr,  pngbytep  transalpha, int\nnumtrans, pngcolor16p transcolor);\n\nvoid pngsettRNStoalpha (pngstructp pngptr);\n\npnguint32  pngsetunknownchunks  (pngstructp  pngptr,   pnginfop   infoptr,   pngun‐\nknownchunkp unknowns, int num, int location);\n\nvoid  pngsetunknownchunklocation (pngstructp pngptr, pnginfop infoptr, int chunk, int\nlocation);\n\nvoid  pngsetuserlimits  (pngstructp  pngptr,  pnguint32  userwidthmax,   pnguint32\nuserheightmax);\n\nvoid  pngsetusertransforminfo  (pngstructp  pngptr,  pngvoidp  usertransformptr, int\nusertransformdepth, int usertransformchannels);\n\nvoid pngsetwritefn  (pngstructp  pngptr,  pngvoidp  ioptr,  pngrwptr  writedatafn,\npngflushptr outputflushfn);\n\nvoid pngsetwritestatusfn (pngstructp pngptr, pngwritestatusptr writerowfn);\n\nvoid    pngsetwriteusertransformfn    (pngstructp    pngptr,    pngusertransformptr\nwriteusertransformfn);\n\nint pngsigcmp (pngbytep sig, sizet start, sizet numtocheck);\n\nvoid pngstartreadimage (pngstructp pngptr);\n\nvoid pngwarning (pngstructp pngptr, pngconstcharp message);\n\nvoid pngwritechunk (pngstructp  pngptr,  pngbytep  chunkname,  pngbytep  data,  sizet\nlength);\n\nvoid pngwritechunkdata (pngstructp pngptr, pngbytep data, sizet length);\n\nvoid pngwritechunkend (pngstructp pngptr);\n\nvoid pngwritechunkstart (pngstructp pngptr, pngbytep chunkname, pnguint32 length);\n\nvoid pngwriteend (pngstructp pngptr, pnginfop infoptr);\n\nvoid pngwriteflush (pngstructp pngptr);\n\nvoid pngwriteimage (pngstructp pngptr, pngbytepp image);\n\nvoid pngwriteinfo (pngstructp pngptr, pnginfop infoptr);\n\nvoid pngwriteinfobeforePLTE (pngstructp pngptr, pnginfop infoptr);\n\nvoid  pngwritepng  (pngstructp  pngptr,  pnginfop  infoptr,  int  transforms, pngvoidp\nparams);\n\nvoid pngwriterow (pngstructp pngptr, pngbytep row);\n\nvoid pngwriterows (pngstructp pngptr, pngbytepp row, pnguint32 numrows);\n\nvoid pngwritesig (pngstructp pngptr);\n\n"
                }
            ]
        },
        "DESCRIPTION": {
            "content": "The libpng library supports encoding, decoding, and various  manipulations  of  the  Portable\nNetwork Graphics (PNG) format image files.  It uses the zlib(3) compression library.  Follow‐\ning is a copy of the libpng-manual.txt file that accompanies libpng.\n\n\nLIBPNG.TXT\nlibpng-manual.txt - A description on how to use and modify libpng\n\nCopyright (c) 2018-2024 Cosmin Truta\nCopyright (c) 1998-2018 Glenn Randers-Pehrson\n\nThis document is released under the libpng license.\nFor conditions of distribution and use, see the disclaimer\nand license in png.h\n\nBased on:\n\nlibpng version 1.6.36, December 2018, through 1.6.43 - February 2024\nUpdated and distributed by Cosmin Truta\nCopyright (c) 2018-2024 Cosmin Truta\n\nlibpng versions 0.97, January 1998, through 1.6.35 - July 2018\nUpdated and distributed by Glenn Randers-Pehrson\nCopyright (c) 1998-2018 Glenn Randers-Pehrson\n\nlibpng 1.0 beta 6 - version 0.96 - May 28, 1997\nUpdated and distributed by Andreas Dilger\nCopyright (c) 1996, 1997 Andreas Dilger\n\nlibpng 1.0 beta 2 - version 0.88 - January 26, 1996\nFor conditions of distribution and use, see copyright\nnotice in png.h. Copyright (c) 1995, 1996 Guy Eric\nSchalnat, Group 42, Inc.\n\nUpdated/rewritten per request in the libpng FAQ\nCopyright (c) 1995, 1996 Frank J. T. Wojcik\nDecember 18, 1995 & January 20, 1996\n\nTABLE OF CONTENTS\n\nI. Introduction\nII. Structures\nIII. Reading\nIV. Writing\nV. Simplified API\nVI. Modifying/Customizing libpng\nVII. MNG support\nVIII. Changes to Libpng from version 0.88\nIX. Changes to Libpng from version 1.0.x to 1.2.x\nX. Changes to Libpng from version 1.0.x/1.2.x to 1.4.x\nXI. Changes to Libpng from version 1.4.x to 1.5.x\nXII. Changes to Libpng from version 1.5.x to 1.6.x\nXIII. Detecting libpng\nXIV. Source code repository\nXV. Coding style\n\n\nI. Introduction\nThis  file  describes  how  to use and modify the PNG reference library (known as libpng) for\nyour own use.  In addition to this file, example.c is a good starting point for using the li‐\nbrary, as it is heavily commented and should include everything most people  will  need.   We\nassume that libpng is already installed; see the INSTALL file for instructions on how to con‐\nfigure and install libpng.\n\nFor  examples  of  libpng usage, see the files \"example.c\", \"pngtest.c\", and the files in the\n\"contrib\" directory, all of which are included in the libpng distribution.\n\nLibpng was written as a companion to the PNG specification, as a way of reducing  the  amount\nof time and effort it takes to support the PNG file format in application programs.\n\nThe  PNG  specification (second edition), November 2003, is available as a W3C Recommendation\nand  as  an  ISO  Standard  (ISO/IEC  15948:2004  (E))  at   <https://www.w3.org/TR/2003/REC-\nPNG-20031110/>.  The W3C and ISO documents have identical technical content.\n\nThe PNG-1.2 specification is available at <https://png-mng.sourceforge.io/pub/png/spec/1.2/>.\nIt  is  technically  equivalent  to the PNG specification (second edition) but has some addi‐\ntional material.\n\nThe  PNG-1.0  specification  is   available   as   RFC   2083   at   <https://png-mng.source‐\nforge.io/pub/png/spec/1.0/>  and  as  a  W3C  Recommendation  at  <https://www.w3.org/TR/REC-\npng-961001>.\n\nSome additional chunks are described  in  the  special-purpose  public  chunks  documents  at\n<http://www.libpng.org/pub/png/spec/register/>\n\nOther  information  about PNG, and the latest version of libpng, can be found at the PNG home\npage, <http://www.libpng.org/pub/png/>.\n\nMost users will not have to modify the library significantly; advanced users may want to mod‐\nify it more.  All attempts were made to make it as complete as possible,  while  keeping  the\ncode  easy  to  understand.  Currently, this library only supports C.  Support for other lan‐\nguages is being considered.\n\nLibpng has been designed to handle multiple sessions at one time, to be easily modifiable, to\nbe portable to the vast majority of machines (ANSI, K&R, 16-, 32-, and 64-bit) available, and\nto be easy to use.  The ultimate goal of libpng is to promote the acceptance of the PNG  file\nformat  in  whatever way possible.  While there is still work to be done (see the TODO file),\nlibpng should cover the majority of the needs of its users.\n\nLibpng uses zlib for its compression and decompression of  PNG  files.   Further  information\nabout  zlib,  and  the  latest  version  of  zlib,  can  be  found  at  the  zlib  home page,\n<https://zlib.net/>.  The zlib compression utility is a general purpose utility that is  use‐\nful for more than PNG files, and can be used without libpng.  See the documentation delivered\nwith zlib for more details.  You can usually find the source files for the zlib utility wher‐\never you find the libpng source files.\n\nLibpng  is thread safe, provided the threads are using different instances of the structures.\nEach thread should have its own pngstruct and pnginfo instances, and thus  its  own  image.\nLibpng does not protect itself against two threads using the same instance of a structure.\n\n\nII. Structures\nThere  are  two  main structures that are important to libpng, pngstruct and pnginfo.  Both\nare internal structures that are no longer exposed in the  libpng  interface  (as  of  libpng\n1.5.0).\n\nThe  pnginfo  structure is designed to provide information about the PNG file.  At one time,\nthe fields of pnginfo were intended to be directly accessible to the  user.   However,  this\ntended  to  cause problems with applications using dynamically loaded libraries, and as a re‐\nsult a set of interface functions for pnginfo (the pngget*()  and  pngset*()  functions)\nwas developed, and direct access to the pnginfo fields was deprecated..\n\nThe  pngstruct  structure is the object used by the library to decode a single image.  As of\n1.5.0 this structure is also not exposed.\n\nAlmost all libpng APIs require a pointer to a pngstruct as the  first  argument.   Many  (in\nparticular the pngset and pngget APIs) also require a pointer to pnginfo as the second ar‐\ngument.   Some  application  visible  macros  defined in png.h designed for basic data access\n(reading and writing integers in the PNG format) don't take a pnginfo pointer, but it's  al‐\nmost always safe to assume that a (pngstruct*) has to be passed to call an API function.\n\nYou  can  have  more  than one pnginfo structure associated with an image, as illustrated in\npngtest.c, one for information valid prior to the IDAT chunks and another (called  \"endinfo\"\nbelow) for things after them.\n\nThe  png.h header file is an invaluable reference for programming with libpng.  And while I'm\non the topic, make sure you include the libpng header file:\n\n#include <png.h>\n\nand also (as of libpng-1.5.0) the zlib header file, if you need it:\n\n#include <zlib.h>\n\n",
            "subsections": [
                {
                    "name": "Types",
                    "content": "The png.h header file defines a number of integral types used by the APIs.  Most of these are\nfairly obvious; for example types corresponding to integers of particular sizes and types for\npassing color values.\n\nOne exception is how non-integral numbers are handled.  For application convenience most APIs\nthat take such numbers have C (double) arguments; however, internally PNG, and libpng, use 32\nbit signed integers and encode the value by multiplying by 100,000.  As  of  libpng  1.5.0  a\nconvenience  macro  PNGFP1 is defined in png.h along with a type (pngfixedpoint) which is\nsimply (pngint32).\n\nAll APIs that take (double) arguments also have a matching API that takes  the  corresponding\nfixed  point  integer arguments.  The fixed point API has the same name as the floating point\none with \"fixed\" appended.  The actual range of values permitted in the APIs  is  frequently\nless  than  the full range of (pngfixedpoint) (-21474 to +21474).  When APIs require a non-\nnegative argument the type is recorded as pnguint32 above.  Consult the header file and the\ntext below for more information.\n\nSpecial care must be take with sCAL chunk handling because the chunk itself uses non-integral\nvalues encoded as strings containing decimal floating point numbers.  See the comments in the\nheader file.\n\n"
                },
                {
                    "name": "Configuration",
                    "content": "The main header file function declarations are frequently protected by C preprocessing direc‐\ntives of the form:\n\n#ifdef PNGfeatureSUPPORTED\ndeclare-function\n#endif\n...\n#ifdef PNGfeatureSUPPORTED\nuse-function\n#endif\n\nThe library can be built without support for these APIs, although a standard build will  have\nall  implemented  APIs.  Application programs should check the feature macros before using an\nAPI for maximum portability.  From libpng 1.5.0 the feature macros set during  the  build  of\nlibpng  are  recorded  in  the header file \"pnglibconf.h\" and this file is always included by\npng.h.\n\nIf you don't need to change the library configuration from the default, skip to the next sec‐\ntion (\"Reading\").\n\nNotice that some of the makefiles in the 'scripts' directory and (in 1.5.0) all of the  build\nproject  files  in  the  'projects'  directory  simply  copy scripts/pnglibconf.h.prebuilt to\npnglibconf.h.  This means that these build systems do not permit easy  auto-configuration  of\nthe library - they only support the default configuration.\n\nThe  easiest way to make minor changes to the libpng configuration when auto-configuration is\nsupported is to add definitions to the command line using (typically) CPPFLAGS.  For example:\n\nCPPFLAGS=-DPNGNOFLOATINGARITHMETIC\n\nwill change the internal libpng math implementation for gamma correction and other arithmetic\ncalculations to fixed point, avoiding the need for fast floating point support.   The  result\ncan  be  seen in the generated pnglibconf.h - make sure it contains the changed feature macro\nsetting.\n\nIf you need to make more extensive configuration changes - more than one or two feature macro\nsettings - you can either add -DPNGUSERCONFIG to the build command line and put a  list  of\nfeature  macro  settings  in pngusr.h or you can set DFAXTRA (a makefile variable) to a file\ncontaining the same information in the form of 'option' settings.\n\nA. Changing pnglibconf.h\n\nA variety of methods exist to build libpng.  Not all  of  these  support  reconfiguration  of\npnglibconf.h.   To  reconfigure  pnglibconf.h  it must either be rebuilt from scripts/pnglib‐\nconf.dfa using awk or it must be edited by hand.\n\nHand editing is achieved by copying scripts/pnglibconf.h.prebuilt to pnglibconf.h and  chang‐\ning  the  lines  defining the supported features, paying very close attention to the 'option'\ninformation in scripts/pnglibconf.dfa that describes those features and  their  requirements.\nThis is easy to get wrong.\n\nB. Configuration using DFAXTRA\n\nRebuilding  from  pnglibconf.dfa  is  easy if a functioning 'awk', or a later variant such as\n'nawk' or 'gawk', is available.  The configure build will automatically find  an  appropriate\nawk and build pnglibconf.h.  The scripts/pnglibconf.mak file contains a set of make rules for\ndoing  the  same thing if configure is not used, and many of the makefiles in the scripts di‐\nrectory use this approach.\n\nWhen rebuilding simply write a new file containing changed options and set  DFAXTRA  to  the\nname  of  this  file.   This  causes  the  build  to  append  the  new  file  to  the  end of\nscripts/pnglibconf.dfa.  The pngusr.dfa file should contain lines of the following forms:\n\neverything = off\n\nThis turns all optional features off.  Include it at the start of pngusr.dfa to make it  eas‐\nier to build a minimal configuration.  You will need to turn at least some features on after‐\nward to enable either reading or writing code, or both.\n\noption feature on option feature off\n\nEnable  or  disable a single feature.  This will automatically enable other features required\nby a feature that is turned on or disable other features that  require  a  feature  which  is\nturned off.  Conflicting settings will cause an error message to be emitted by awk.\n\nsetting feature default value\n\nChanges  the default value of setting 'feature' to 'value'.  There are a small number of set‐\ntings listed at the top of pnglibconf.h, they are documented in the  source  code.   Most  of\nthese  values  have performance implications for the library but most of them have no visible\neffect on the API.  Some can also be overridden from the API.\n\nThis method of building a customized pnglibconf.h is illustrated in contrib/pngminim/*.   See\nthe \"$(PNGCONF):\" target in the makefile and pngusr.dfa in these directories.\n\nC. Configuration using PNGUSERCONFIG\n\nIf  -DPNGUSERCONFIG  is added to the CPPFLAGS when pnglibconf.h is built, the file pngusr.h\nwill automatically be included before the options in  scripts/pnglibconf.dfa  are  processed.\nYour  pngusr.h  file should contain only macro definitions turning features on or off or set‐\nting settings.\n\nApart from the global setting \"everything = off\" all the options listed above can be set  us‐\ning macros in pngusr.h:\n\n#define PNGfeatureSUPPORTED\n\nis equivalent to:\n\noption feature on\n\n#define PNGNOfeature\n\nis equivalent to:\n\noption feature off\n\n#define PNGfeature value\n\nis equivalent to:\n\nsetting feature default value\n\nNotice  that in both cases, pngusr.dfa and pngusr.h, the contents of the pngusr file you sup‐\nply override the contents of scripts/pnglibconf.dfa\n\nIf confusing or incomprehensible behavior results it is possible to examine the  intermediate\nfile  pnglibconf.dfn  to find the full set of dependency information for each setting and op‐\ntion.  Simply locate the feature in the file and read the C comments that precede it.\n\nThis method is also illustrated in the contrib/pngminim/* makefiles and pngusr.h.\n\n\nIII. Reading\nWe'll now walk you through the possible functions to call when reading in a PNG file  sequen‐\ntially,  briefly  explaining the syntax and purpose of each one.  See example.c and png.h for\nmore detail.  While progressive reading is covered in the next section, you will  still  need\nsome of the functions discussed in this section to read a PNG file.\n\n"
                },
                {
                    "name": "Setup",
                    "content": "You  will  want  to do the I/O initialization(*) before you get into libpng, so if it doesn't\nwork, you don't have much to undo.  Of course, you will also want to insure that you are,  in\nfact,  dealing  with  a  PNG  file.  Libpng provides a simple check to see if a file is a PNG\nfile.  To use it, pass in the first 1 to 8 bytes of the file to the  function  pngsigcmp(),\nand it will return 0 (false) if the bytes match the corresponding bytes of the PNG signature,\nor nonzero (true) otherwise.  Of course, the more bytes you pass in, the greater the accuracy\nof the prediction.\n\nIf  you  are  intending  to keep the file pointer open for use in libpng, you must ensure you\ndon't read more than 8 bytes from the beginning of the file, and you also have to make a call\nto pngsetsigbytes() with the number of bytes you read from  the  beginning.   Libpng  will\nthen only check the bytes (if any) that your program didn't read.\n\n(*): If you are not using the standard I/O functions, you will need to replace them with cus‐\ntom functions.  See the discussion under Customizing libpng.\n\nFILE *fp = fopen(filename, \"rb\");\nif (!fp)\n{\nreturn ERROR;\n}\n\nif (fread(header, 1, number, fp) != number)\n{\nreturn ERROR;\n}\n\nispng = (pngsigcmp(header, 0, number) == 0);\nif (!ispng)\n{\nreturn NOTPNG;\n}\n\nNext,  pngstruct and pnginfo need to be allocated and initialized.  In order to ensure that\nthe size of these structures is correct even with a  dynamically  linked  libpng,  there  are\nfunctions  to  initialize and allocate the structures.  We also pass the library version, op‐\ntional pointers to error handling functions, and a pointer to a data struct for  use  by  the\nerror  functions,  if  necessary  (the pointer and functions can be NULL if the default error\nhandlers are to be used).  See the section on Changes to Libpng below regarding the old  ini‐\ntialization  functions.   The structure allocation functions quietly return NULL if they fail\nto create the structure, so your application should check for that.\n\npngstructp pngptr = pngcreatereadstruct\n(PNGLIBPNGVERSTRING, (pngvoidp)usererrorptr,\nusererrorfn, userwarningfn);\n\nif (!pngptr)\nreturn ERROR;\n\npnginfop infoptr = pngcreateinfostruct(pngptr);\n\nif (!infoptr)\n{\npngdestroyreadstruct(&pngptr, NULL, NULL);\nreturn ERROR;\n}\n\nIf you want to use your own memory allocation routines, use a  libpng  that  was  built  with\nPNGUSERMEMSUPPORTED  defined,  and  use  pngcreatereadstruct2()  instead  of  pngcre‐\natereadstruct():\n\npngstructp pngptr = pngcreatereadstruct2\n(PNGLIBPNGVERSTRING, (pngvoidp)usererrorptr,\nusererrorfn, userwarningfn, (pngvoidp)\nusermemptr, usermallocfn, userfreefn);\n\nThe error handling routines passed to pngcreatereadstruct() and the memory alloc/free rou‐\ntines passed to pngcreatestruct2() are only necessary if you are not using the libpng sup‐\nplied error handling and memory alloc/free functions.\n\nWhen libpng encounters an error, it expects to longjmp back to your routine.  Therefore,  you\nwill  need  to call setjmp and pass your pngjmpbuf(pngptr).  If you read the file from dif‐\nferent routines, you will need to update the longjmp buffer every time you enter a  new  rou‐\ntine that will call a png*() function.\n\nSee  your  documentation  of  setjmp/longjmp  for  your  compiler  for  more  information  on\nsetjmp/longjmp.  See the discussion on libpng error handling in the Customizing  Libpng  sec‐\ntion below for more information on the libpng error handling.  If an error occurs, and libpng\nlongjmp's  back  to  your setjmp, you will want to call pngdestroyreadstruct() to free any\nmemory.\n\nif (setjmp(pngjmpbuf(pngptr)))\n{\npngdestroyreadstruct(&pngptr, &infoptr, &endinfo);\nfclose(fp);\nreturn ERROR;\n}\n\nPass NULL instead of &endinfo if you didn't create an endinfo structure.\n\nIf you would rather avoid the complexity of setjmp/longjmp issues,  you  can  compile  libpng\nwith  PNGNOSETJMP, in which case errors will result in a call to PNGABORT() which defaults\nto abort().\n\nYou can #define PNGABORT() to a function that does something more useful  than  abort(),  as\nlong as your function does not return.\n\nNow  you  need  to  set  up  the input code.  The default for libpng is to use the C function\nfread().  If you  use  this,  you  will  need  to  pass  a  valid  FILE  *  in  the  function\npnginitio().   Be sure that the file is opened in binary mode.  If you wish to handle read‐\ning data in another way, you need not call the pnginitio() function, but you must then  im‐\nplement the libpng I/O methods discussed in the Customizing Libpng section below.\n\npnginitio(pngptr, fp);\n\nIf you had previously opened the file and read any of the signature from the beginning in or‐\nder  to  see  if  this  was a PNG file, you need to let libpng know that there are some bytes\nmissing from the start of the file.\n\npngsetsigbytes(pngptr, number);\n\nYou can change the zlib compression buffer size to be used while reading compressed data with\n\npngsetcompressionbuffersize(pngptr, buffersize);\n\nwhere the default size is 8192 bytes.  Note that the buffer size is changed  immediately  and\nthe buffer is reallocated immediately, instead of setting a flag to be acted upon later.\n\nIf you want CRC errors to be handled in a different manner than the default, use\n\npngsetcrcaction(pngptr, critaction, ancilaction);\n\nThe  values  for pngsetcrcaction() say how libpng is to handle CRC errors in ancillary and\ncritical chunks, and whether to use the data contained therein. Starting with  libpng-1.6.26,\nthis  also governs how an ADLER32 error is handled while reading the IDAT chunk. Note that it\nis impossible to \"discard\" data in a critical chunk.\n\nChoices for (int) critaction are\nPNGCRCDEFAULT      0  error/quit\nPNGCRCERRORQUIT   1  error/quit\nPNGCRCWARNUSE     3  warn/use data\nPNGCRCQUIETUSE    4  quiet/use data\nPNGCRCNOCHANGE    5  use the current value\n\nChoices for (int) ancilaction are\nPNGCRCDEFAULT      0  error/quit\nPNGCRCERRORQUIT   1  error/quit\nPNGCRCWARNDISCARD 2  warn/discard data\nPNGCRCWARNUSE     3  warn/use data\nPNGCRCQUIETUSE    4  quiet/use data\nPNGCRCNOCHANGE    5  use the current value\n\nWhen the setting for critaction is PNGCRCQUIETUSE, the CRC and ADLER32 checksums are  not\nonly ignored, but they are not evaluated.\n\n"
                },
                {
                    "name": "Setting up callback code",
                    "content": "You can set up a callback function to handle any unknown chunks in the input stream. You must\nsupply the function\n\nreadchunkcallback(pngstructp pngptr,\npngunknownchunkp chunk)\n{\n/* The unknown chunk structure contains your\nchunk data, along with similar data for any other\nunknown chunks: */\n\npngbyte name[5];\npngbyte *data;\nsizet size;\n\n/* Note that libpng has already taken care of\nthe CRC handling */\n\n/* put your code here.  Search for your chunk in the\nunknown chunk structure, process it, and return one\nof the following: */\n\nreturn -n; /* chunk had an error */\nreturn 0; /* did not recognize */\nreturn n; /* success */\n}\n\n(You can give your function another name that you like instead of \"readchunkcallback\")\n\nTo inform libpng about your function, use\n\npngsetreaduserchunkfn(pngptr, userchunkptr,\nreadchunkcallback);\n\nThis names not only the callback function, but also a user pointer that you can retrieve with\n\npnggetuserchunkptr(pngptr);\n\nIf  you  call  the  pngsetreaduserchunkfn()  function, then all unknown chunks which the\ncallback does not handle will be saved when read.  You can cause them to be discarded by  re‐\nturning  '1' (\"handled\") instead of '0'.  This behavior will change in libpng 1.7 and the de‐\nfault handling set by the pngsetkeepunknownchunks() function, described  below,  will  be\nused  when  the  callback  returns  0.   If you want the existing behavior you should set the\nglobal default to PNGHANDLECHUNKIFSAFE now; this is compatible with all current  versions\nof  libpng  and  with  1.7.  Libpng 1.6 issues a warning if you keep the default, or PNGHAN‐\nDLECHUNKNEVER, and the callback returns 0.\n\nAt this point, you can set up a callback function that will be called after each row has been\nread, which you can use to control a progress  meter  or  the  like.   It's  demonstrated  in\npngtest.c.  You must supply a function\n\nvoid readrowcallback(pngstructp pngptr,\npnguint32 row, int pass)\n{\n/* put your code here */\n}\n\n(You can give it another name that you like instead of \"readrowcallback\")\n\nTo inform libpng about your function, use\n\npngsetreadstatusfn(pngptr, readrowcallback);\n\nWhen  this function is called the row has already been completely processed and the 'row' and\n'pass' refer to the next row to be handled.  For the non-interlaced case  the  row  that  was\njust  handled  is  simply  one less than the passed in row number, and pass will always be 0.\nFor the interlaced case the same applies unless the row value is 0, in  which  case  the  row\njust handled was the last one from one of the preceding passes.  Because interlacing may skip\na  pass  you  cannot  be sure that the preceding pass is just 'pass-1'; if you really need to\nknow what the last pass is record (row,pass) from the callback  and  use  the  last  recorded\nvalue each time.\n\nAs with the user transform you can find the output row using the PNGROWFROMPASSROW macro.\n\n"
                },
                {
                    "name": "Unknown-chunk handling",
                    "content": "Now you get to set the way the library processes unknown chunks in the input PNG stream. Both\nknown  and  unknown chunks will be read.  Normal behavior is that known chunks will be parsed\ninto information in various infoptr members while unknown chunks will be discarded. This be‐\nhavior can be wasteful if your application will never use some known chunk types.  To  change\nthis, you can call:\n\npngsetkeepunknownchunks(pngptr, keep,\nchunklist, numchunks);\n\nkeep       - 0: default unknown chunk handling\n1: ignore; do not keep\n2: keep only if safe-to-copy\n3: keep even if unsafe-to-copy\n\nYou can use these definitions:\nPNGHANDLECHUNKASDEFAULT   0\nPNGHANDLECHUNKNEVER        1\nPNGHANDLECHUNKIFSAFE      2\nPNGHANDLECHUNKALWAYS       3\n\nchunklist - list of chunks affected (a byte string,\nfive bytes per chunk, NULL or ' ' if\nnumchunks is positive; ignored if\nnumchunks <= 0).\n\nnumchunks - number of chunks affected; if 0, all\nunknown chunks are affected.  If positive,\nonly the chunks in the list are affected,\nand if negative all unknown chunks and\nall known chunks except for the IHDR,\nPLTE, tRNS, IDAT, and IEND chunks are\naffected.\n\nUnknown  chunks  declared  in  this  way  will  be  saved  as raw data onto a list of pngun‐\nknownchunk structures.  If a chunk that is normally known to libpng is named in the list, it\nwill be handled as unknown, according to the \"keep\" directive.  If a chunk is named  in  suc‐\ncessive  instances of pngsetkeepunknownchunks(), the final instance will take precedence.\nThe IHDR and IEND chunks should not be named in chunklist; if they are, libpng will  process\nthem normally anyway.  If you know that your application will never make use of some particu‐\nlar chunks, use PNGHANDLECHUNKNEVER (or 1) as demonstrated below.\n\nHere  is  an  example of the usage of pngsetkeepunknownchunks(), where the private \"vpAg\"\nchunk will later be processed by a user chunk callback function:\n\npngbyte vpAg[5]={118, 112,  65, 103, (pngbyte) ' '};\n\n#if defined(PNGUNKNOWNCHUNKSSUPPORTED)\npngbyte unusedchunks[]=\n{\n104,  73,  83,  84, (pngbyte) ' ',   /* hIST */\n105,  84,  88, 116, (pngbyte) ' ',   /* iTXt */\n112,  67,  65,  76, (pngbyte) ' ',   /* pCAL */\n115,  67,  65,  76, (pngbyte) ' ',   /* sCAL */\n115,  80,  76,  84, (pngbyte) ' ',   /* sPLT */\n116,  73,  77,  69, (pngbyte) ' ',   /* tIME */\n};\n#endif\n\n...\n\n#if defined(PNGUNKNOWNCHUNKSSUPPORTED)\n/* ignore all unknown chunks\n* (use global setting \"2\" for libpng16 and earlier):\n*/\npngsetkeepunknownchunks(readptr, 2, NULL, 0);\n\n/* except for vpAg: */\npngsetkeepunknownchunks(readptr, 2, vpAg, 1);\n\n/* also ignore unused known chunks: */\npngsetkeepunknownchunks(readptr, 1, unusedchunks,\n(int)(sizeof unusedchunks)/5);\n#endif\n\n"
                },
                {
                    "name": "User limits",
                    "content": "The PNG specification allows the width and height of an image  to  be  as  large  as  2^(31-1\n(0x7fffffff),  or about 2.147 billion rows and columns.  For safety, libpng imposes a default\nlimit of 1 million rows and columns.  Larger images  will  be  rejected  immediately  with  a\npngerror() call. If you wish to change these limits, you can use\n\npngsetuserlimits(pngptr, widthmax, heightmax);\n\nto  set  your own limits (libpng may reject some very wide images anyway because of potential\nbuffer overflow conditions).\n\nYou should put this  statement  after  you  create  the  PNG  structure  and  before  calling\npngreadinfo(), pngreadpng(), or pngprocessdata().\n\nWhen  writing  a  PNG  datastream,  put  this  statement  before  calling pngwriteinfo() or\npngwritepng().\n\nIf you need to retrieve the limits that are being applied, use\n\nwidthmax = pnggetuserwidthmax(pngptr);\nheightmax = pnggetuserheightmax(pngptr);\n\nThe PNG specification sets no limit on the number of ancillary chunks allowed in a PNG datas‐\ntream.  By default, libpng imposes a limit of a total of 1000 sPLT, tEXt, iTXt, zTXt, and un‐\nknown chunks to be stored.  If you have set up both infoptr and endinfoptr, the limit  ap‐\nplies  separately  to each.  You can change the limit on the total number of such chunks that\nwill be stored, with\n\npngsetchunkcachemax(pngptr, userchunkcachemax);\n\nwhere 0x7fffffffL means unlimited.  You can retrieve this limit with\n\nchunkcachemax = pnggetchunkcachemax(pngptr);\n\nLibpng imposes a limit of 8 Megabytes (8,000,000 bytes) on the  amount  of  memory  that  any\nchunk other than IDAT can occupy, originally or when decompressed (prior to libpng-1.6.32 the\nlimit  was  only applied to compressed chunks after decompression). You can change this limit\nwith\n\npngsetchunkmallocmax(pngptr, userchunkmallocmax);\n\nand you can retrieve the limit with\n\nchunkmallocmax = pnggetchunkmallocmax(pngptr);\n\nAny chunks that would cause either of these limits to be exceeded will be ignored.\n\n"
                },
                {
                    "name": "Information about your system",
                    "content": "If you intend to display the PNG or to incorporate it in other image data you  need  to  tell\nlibpng  information about your display or drawing surface so that libpng can convert the val‐\nues in the image to match the display.\n\nFrom libpng-1.5.4 this information can be set before reading the PNG file header.  In earlier\nversions pngsetgamma() existed but behaved incorrectly if called before the PNG file header\nhad been read and pngsetalphamode() did not exist.\n\nIf you need to support versions prior to libpng-1.5.4 test the version number as  illustrated\nbelow  using \"PNGLIBPNGVER >= 10504\" and follow the procedures described in the appropriate\nmanual page.\n\nYou give libpng the encoding expected by your system expressed as a 'gamma' value.   You  can\nalso  specify a default encoding for the PNG file in case the required information is missing\nfrom the file.  By default libpng assumes that the PNG data matches your system, to keep this\ndefault call:\n\npngsetgamma(pngptr, screengamma, outputgamma);\n\nor you can use the fixed point equivalent:\n\npngsetgammafixed(pngptr, PNGFP1*screengamma,\nPNGFP1*outputgamma);\n\nIf you don't know the gamma for your system it is probably 2.2 - a good approximation to  the\nIEC  standard  for display systems (sRGB).  If images are too contrasty or washed out you got\nthe value wrong - check your system documentation!\n\nMany systems permit the system gamma to be changed via a lookup table in the display  driver,\na  few systems, including older Macs, change the response by default.  As of 1.5.4 three spe‐\ncial values are available to handle common situations:\n\nPNGDEFAULTsRGB: Indicates that the system conforms to the\nIEC 61966-2-1 standard.  This matches almost\nall systems.\nPNGGAMMAMAC18: Indicates that the system is an older\n(pre Mac OS 10.6) Apple Macintosh system with\nthe default settings.\nPNGGAMMALINEAR: Just the fixed point value for 1.0 - indicates\nthat the system expects data with no gamma\nencoding.\n\nYou would use the linear (unencoded) value if you need to process the  pixel  values  further\nbecause this avoids the need to decode and re-encode each component value whenever arithmetic\nis  performed.   A  lot  of  graphics software uses linear values for this reason, often with\nhigher precision component values to preserve overall accuracy.\n\n\nThe outputgamma value expresses how to decode the output values, not how they  are  encoded.\nThe values used correspond to the normal numbers used to describe the overall gamma of a com‐\nputer  display  system; for example 2.2 for an sRGB conformant system.  The values are scaled\nby 100000 in the fixed version of the API (so 220000 for sRGB.)\n\nThe inverse of the value is always used to provide a default for the PNG file encoding if  it\nhas no gAMA chunk and if pngsetgamma() has not been called to override the PNG gamma infor‐\nmation.\n\nWhen  the  ALPHAOPTIMIZED  mode is selected the output gamma is used to encode opaque pixels\nhowever pixels with lower alpha values are not encoded, regardless of the output  gamma  set‐\nting.\n\nWhen the standard Porter Duff handling is requested with mode 1 the output encoding is set to\nbe linear and the outputgamma value is only relevant as a default for input data that has no\ngamma  information.   The  linear  output  encoding  will be overridden if pngsetgamma() is\ncalled - the results may be highly unexpected!\n\nThe following numbers are derived from the sRGB standard and the research behind it.  sRGB is\ndefined to be approximated by a PNG gAMA chunk value of 0.45455 (1/2.2) for PNG.   The  value\nimplicitly includes any viewing correction required to take account of any differences in the\ncolor  environment  of the original scene and the intended display environment; the value ex‐\npresses how to *decode* the image for display, not how the original data was *encoded*.\n\nsRGB provides a peg for the PNG standard by defining a viewing environment.  sRGB itself, and\nearlier TV standards, actually use a more complex transform (a linear portion  then  a  gamma\n2.4  power law) than PNG can express.  (PNG is limited to simple power laws.)  By saying that\nan image for direct display on an sRGB conformant system should be stored with a  gAMA  chunk\nvalue  of  45455  (11.3.3.2  and 11.3.3.5 of the ISO PNG specification) the PNG specification\nmakes it possible to derive values for other display systems and environments.\n\nThe Mac value is deduced from the sRGB based on an assumption that the actual  extra  viewing\ncorrection used in early Mac display systems was implemented as a power 1.45 lookup table.\n\nAny  system where a programmable lookup table is used or where the behavior of the final dis‐\nplay device characteristics can be changed requires system specific code to obtain  the  cur‐\nrent  characteristic.   However  this can be difficult and most PNG gamma correction only re‐\nquires an approximate value.\n\nBy default, if pngsetalphamode() is not called, libpng assumes that all values  are  unen‐\ncoded,  linear,  values and that the output device also has a linear characteristic.  This is\nonly very rarely correct - it is invariably better to call pngsetalphamode() with  PNGDE‐\nFAULTsRGB than rely on the default if you don't know what the right answer is!\n\nThe special value PNGGAMMAMAC18 indicates an older Mac system (pre Mac OS 10.6) which used\na correction table to implement a somewhat lower gamma on an otherwise sRGB system.\n\nBoth  these values are reserved (not simple gamma values) in order to allow more precise cor‐\nrection internally in the future.\n\nNOTE: the values can be passed to either the fixed or floating point APIs, but  the  floating\npoint API will also accept floating point values.\n\nThe  second  thing you may need to tell libpng about is how your system handles alpha channel\ninformation.  Some, but not all, PNG files contain an alpha channel.  To display these  files\ncorrectly  you  need  to compose the data onto a suitable background, as described in the PNG\nspecification.\n\nLibpng only supports composing onto a single color  (using  pngsetbackground;  see  below).\nOtherwise  you  must  do  the  composition  yourself  and, in this case, you may need to call\npngsetalphamode:\n\n#if PNGLIBPNGVER >= 10504\npngsetalphamode(pngptr, mode, screengamma);\n#else\npngsetgamma(pngptr, screengamma, 1.0/screengamma);\n#endif\n\nThe screengamma value is the same as the argument to pngsetgamma; however, how it  affects\nthe  output  depends  on  the  mode.   pngsetalphamode()  sets  the  file gamma default to\n1/screengamma, so normally you don't need to call pngsetgamma.  If you need different  de‐\nfaults  call pngsetgamma() before pngsetalphamode() - if you call it after it will over‐\nride the settings made by pngsetalphamode().\n\nThe mode is as follows:\n\nPNGALPHAPNG: The data is encoded according to the PNG specification.   Red,  green  and\nblue, or gray, components are gamma encoded color values and are not premultiplied by the al‐\npha  value.  The alpha value is a linear measure of the contribution of the pixel to the cor‐\nresponding final output pixel.\n\nYou should normally use this format if you intend to perform color correction  on  the  color\nvalues; most, maybe all, color correction software has no handling for the alpha channel and,\nanyway, the math to handle pre-multiplied component values is unnecessarily complex.\n\nBefore  you  do  any arithmetic on the component values you need to remove the gamma encoding\nand multiply out the alpha channel.  See the PNG specification for more detail.  It is impor‐\ntant to note that when an image with an alpha channel is scaled, linear  encoded,  pre-multi‐\nplied component values must be used!\n\nThe  remaining  modes assume you don't need to do any further color correction or that if you\ndo, your color correction software knows all about alpha (it probably doesn't!).  They 'asso‐\nciate' the alpha with the color information by storing color channel values  that  have  been\nscaled  by  the  alpha.  The advantage is that the color channels can be resampled (the image\ncan be scaled) in this form.  The disadvantage is that normal practice is  to  store  linear,\nnot  (gamma)  encoded,  values and this requires 16-bit channels for still images rather than\nthe 8-bit channels that are just about sufficient if gamma encoding is used.  In addition all\nnon-transparent pixel values, including completely opaque ones, must be gamma encoded to pro‐\nduce the final image.  These are the 'STANDARD', 'ASSOCIATED' or  'PREMULTIPLIED'  modes  de‐\nscribed  below  (the  latter being the two common names for associated alpha color channels).\nNote that PNG files always contain non-associated color channels;  pngsetalphamode()  with\none  of  the  modes causes the decoder to convert the pixels to an associated form before re‐\nturning them to your application.\n\nSince it is not necessary to perform arithmetic on opaque color values so long  as  they  are\nnot  to be resampled and are in the final color space it is possible to optimize the handling\nof alpha by storing the opaque pixels in the PNG format (adjusted for the output color space)\nwhile storing partially opaque pixels in the standard, linear, format.  The accuracy required\nfor standard alpha composition is relatively low, because the pixels are isolated,  therefore\ntypically  the accuracy loss in storing 8-bit linear values is acceptable.  (This is not true\nif the alpha channel is used to simulate transparency over large areas - use 16 bits  or  the\nPNG  mode  in this case!)  This is the 'OPTIMIZED' mode.  For this mode a pixel is treated as\nopaque only if the alpha value is equal to the maximum value.\n\nPNGALPHASTANDARD:  The data libpng produces is encoded in the standard way  assumed  by\nmost  correctly  written graphics software.  The gamma encoding will be removed by libpng and\nthe linear component values will be pre-multiplied by the alpha channel.\n\nWith this format the final image must be re-encoded to match the display gamma before the im‐\nage is displayed.  If your system doesn't do that, yet still seems to perform  arithmetic  on\nthe pixels without decoding them, it is broken - check out the modes below.\n\nWith PNGALPHASTANDARD libpng always produces linear component values, whatever screengamma\nyou  supply.  The screengamma value is, however, used as a default for the file gamma if the\nPNG file has no gamma information.\n\nIf you call pngsetgamma() after pngsetalphamode() you will override the linear encoding.\nInstead the pre-multiplied pixel values will be gamma encoded  but  the  alpha  channel  will\nstill be linear.  This may actually match the requirements of some broken software, but it is\nunlikely.\n\nWhile linear 8-bit data is often used it has insufficient precision for any image with a rea‐\nsonable  dynamic range.  To avoid problems, and if your software supports it, use pngsetex‐\npand16() to force all components to 16 bits.\n\nPNGALPHAOPTIMIZED: This mode is the same as PNGALPHASTANDARD except  that  completely\nopaque  pixels are gamma encoded according to the screengamma value.  Pixels with alpha less\nthan 1.0 will still have linear components.\n\nUse this format if you have control over your compositing software  and  so  don't  do  other\narithmetic  (such as scaling) on the data you get from libpng.  Your compositing software can\nsimply copy opaque pixels to the output but still has linear values for the  non-opaque  pix‐\nels.\n\nIn  normal compositing, where the alpha channel encodes partial pixel coverage (as opposed to\nbroad area translucency), the inaccuracies of the 8-bit representation of  non-opaque  pixels\nare irrelevant.\n\nYou can also try this format if your software is broken; it might look better.\n\nPNGALPHABROKEN:  This  is  PNGALPHASTANDARD; however, all component values, including\nthe alpha channel are gamma encoded.  This is broken because, in practice, no  implementation\nthat  uses  this choice correctly undoes the encoding before handling alpha composition.  Use\nthis choice only if other serious errors in the software or hardware you use mandate it.   In\nmost  cases of broken software or hardware the bug in the final display manifests as a subtle\nhalo around composited parts of the image.  You may not even perceive this  as  a  halo;  the\ncomposited part of the image may simply appear separate from the background, as though it had\nbeen cut out of paper and pasted on afterward.\n\nIf  you  don't  have to deal with bugs in software or hardware, or if you can fix them, there\nare three recommended ways of using pngsetalphamode():\n\npngsetalphamode(pngptr, PNGALPHAPNG,\nscreengamma);\n\nYou can do color correction on the result (libpng does not currently support color correction\ninternally).  When you handle the alpha channel you need to undo the gamma encoding and  mul‐\ntiply out the alpha.\n\npngsetalphamode(pngptr, PNGALPHASTANDARD,\nscreengamma);\npngsetexpand16(pngptr);\n\nIf  you  are  using  the  high  level interface, don't call pngsetexpand16(); instead pass\nPNGTRANSFORMEXPAND16 to the interface.\n\nWith this mode you can't do color correction, but you can do arithmetic,  including  composi‐\ntion and scaling, on the data without further processing.\n\npngsetalphamode(pngptr, PNGALPHAOPTIMIZED,\nscreengamma);\n\nYou  can avoid the expansion to 16-bit components with this mode, but you lose the ability to\nscale the image or perform other linear arithmetic.  All you can do  is  compose  the  result\nonto  a  matching output.  Since this mode is libpng-specific you also need to write your own\ncomposition software.\n\nThe following are examples of calls to pngsetalphamode to  achieve  the  required  overall\ngamma correction and, where necessary, alpha premultiplication.\n\npngsetalphamode(pp, PNGALPHAPNG, PNGDEFAULTsRGB);\n\nChoices for the alphamode are\n\nPNGALPHAPNG           0 /* according to the PNG standard */\nPNGALPHASTANDARD      1 /* according to Porter/Duff */\nPNGALPHAASSOCIATED    1 /* as above; this is the normal practice */\nPNGALPHAPREMULTIPLIED 1 /* as above */\nPNGALPHAOPTIMIZED     2 /* 'PNG' for opaque pixels, else 'STANDARD' */\nPNGALPHABROKEN        3 /* the alpha channel is gamma encoded */\n\nPNGALPHAPNG  is  the default libpng handling of the alpha channel. It is not pre-multiplied\ninto the color components. In addition the call states that the output is for a  sRGB  system\nand causes all PNG files without gAMA chunks to be assumed to be encoded using sRGB.\n\npngsetalphamode(pp, PNGALPHAPNG, PNGGAMMAMAC);\n\nIn  this  case the output is assumed to be something like an sRGB conformant display preceded\nby a power-law lookup table of power 1.45.  This is how early Mac systems behaved.\n\npngsetalphamode(pp, PNGALPHASTANDARD, PNGGAMMALINEAR);\n\nThis is the classic Jim Blinn approach and will work in academic  environments  where  every‐\nthing  is  done  by the book.  It has the shortcoming of assuming that input PNG data with no\ngamma information is linear - this is unlikely to be correct unless the PNG files were gener‐\nated locally.  Most of the time the output precision will be so low as  to  show  significant\nbanding in dark areas of the image.\n\npngsetexpand16(pp);\npngsetalphamode(pp, PNGALPHASTANDARD, PNGDEFAULTsRGB);\n\nThis is a somewhat more realistic Jim Blinn inspired approach.  PNG files are assumed to have\nthe  sRGB encoding if not marked with a gamma value and the output is always 16 bits per com‐\nponent.  This permits accurate scaling and processing of the data.  If you know that your in‐\nput PNG files were generated locally you might need to replace PNGDEFAULTsRGB with the cor‐\nrect value for your system.\n\npngsetalphamode(pp, PNGALPHAOPTIMIZED, PNGDEFAULTsRGB);\n\nIf you just need to composite the PNG image onto an existing background and  if  you  control\nthe  code  that  does  this you can use the optimization setting.  In this case you just copy\ncompletely opaque pixels to the output.  For pixels that are not completely transparent  (you\njust  skip  those)  you do the composition math using pngcomposite or pngcomposite16 below\nthen encode the resultant 8-bit or 16-bit values to match the output encoding.\n\nOther cases\n\nIf neither the PNG nor the standard linear encoding work for you because of the  software  or\nhardware  you  use  then  you have a big problem.  The PNG case will probably result in halos\naround the image.  The linear encoding will probably result in a washed out, too bright,  im‐\nage  (it's  actually too contrasty.)  Try the ALPHAOPTIMIZED mode above - this will probably\nsubstantially reduce the halos.  Alternatively try:\n\npngsetalphamode(pp, PNGALPHABROKEN, PNGDEFAULTsRGB);\n\nThis option will also reduce the halos, but there will be slight dark halos round the  opaque\nparts  of  the  image where the background is light.  In the OPTIMIZED mode the halos will be\nlight halos where the background is dark.  Take your pick - the halos are unavoidable  unless\nyou can get your hardware/software fixed!  (The OPTIMIZED approach is slightly faster.)\n\nWhen  the  default  gamma of PNG files doesn't match the output gamma.  If you have PNG files\nwith no gamma information pngsetalphamode allows you to provide a default  gamma,  but  it\nalso  sets  the  output gamma to the matching value.  If you know your PNG files have a gamma\nthat doesn't match the output you can take advantage of the fact that pngsetalphamode  al‐\nways sets the output gamma but only sets the PNG default if it is not already set:\n\npngsetalphamode(pp, PNGALPHAPNG, PNGDEFAULTsRGB);\npngsetalphamode(pp, PNGALPHAPNG, PNGGAMMAMAC);\n\nThe  first  call sets both the default and the output gamma values, the second call overrides\nthe output gamma without changing the default.  This is easier than achieving the same effect\nwith pngsetgamma.  You must use PNGALPHAPNG for the first call  -  internal  checking  in\npngsetalpha will fire if more than one call to pngsetalphamode and pngsetbackground is\nmade in the same read operation, however multiple calls with PNGALPHAPNG are ignored.\n\nIf  you  don't  need, or can't handle, the alpha channel you can call pngsetbackground() to\nremove it by compositing against a fixed color.  Don't call pngsetstripalpha() to do  this\n- it will leave spurious pixel values in transparent parts of this image.\n\npngsetbackground(pngptr, &backgroundcolor,\nPNGBACKGROUNDGAMMASCREEN, 0, 1);\n\nThe  backgroundcolor  is  an RGB or grayscale value according to the data format libpng will\nproduce for you.  Because you don't yet know  the  format  of  the  PNG  file,  if  you  call\npngsetbackground at this point you must arrange for the format produced by libpng to always\nhave  8-bit  or 16-bit components and then store the color as an 8-bit or 16-bit color as ap‐\npropriate.  The color contains separate gray and RGB component values, so you can let  libpng\nproduce  gray or RGB output according to the input format, but low bit depth grayscale images\nmust always be converted to at least 8-bit format.  (Even though low bit depth grayscale  im‐\nages can't have an alpha channel they can have a transparent color!)\n\nYou  set the transforms you need later, either as flags to the high level interface or libpng\nAPI calls for the low level interface.  For reference the settings  and  API  calls  required\nare:\n\n8-bit values:\nPNGTRANSFORMSCALE16 | PNGEXPAND\npngsetexpand(pngptr); pngsetscale16(pngptr);\n\nIf you must get exactly the same inaccurate results\nproduced by default in versions prior to libpng-1.5.4,\nuse PNGTRANSFORMSTRIP16 and pngsetstrip16(pngptr)\ninstead.\n\n16-bit values:\nPNGTRANSFORMEXPAND16\npngsetexpand16(pngptr);\n\nIn  either  case palette image data will be expanded to RGB.  If you just want color data you\ncan add PNGTRANSFORMGRAYTORGB or pngsetgraytorgb(pngptr) to the list.\n\nCalling pngsetbackground before the PNG  file  header  is  read  will  not  work  prior  to\nlibpng-1.5.4.   Because  the failure may result in unexpected warnings or errors it is there‐\nfore much safer to call pngsetbackground after the head has been read.  Unfortunately  this\nmeans that prior to libpng-1.5.4 it cannot be used with the high level interface.\n\n"
                },
                {
                    "name": "The high-level read interface",
                    "content": "At  this  point  there  are  two  ways  to proceed; through the high-level read interface, or\nthrough a sequence of low-level read operations.  You can use the high-level interface if (a)\nyou are willing to read the entire image into memory, and (b) the input  transformations  you\nwant to do are limited to the following set:\n\nPNGTRANSFORMIDENTITY      No transformation\nPNGTRANSFORMSCALE16      Strip 16-bit samples to\n8-bit accurately\nPNGTRANSFORMSTRIP16      Chop 16-bit samples to\n8-bit less accurately\nPNGTRANSFORMSTRIPALPHA   Discard the alpha channel\nPNGTRANSFORMPACKING       Expand 1, 2 and 4-bit\nsamples to bytes\nPNGTRANSFORMPACKSWAP      Change order of packed\npixels to LSB first\nPNGTRANSFORMEXPAND        Perform setexpand()\nPNGTRANSFORMINVERTMONO   Invert monochrome images\nPNGTRANSFORMSHIFT         Normalize pixels to the\nsBIT depth\nPNGTRANSFORMBGR           Flip RGB to BGR, RGBA\nto BGRA\nPNGTRANSFORMSWAPALPHA    Flip RGBA to ARGB or GA\nto AG\nPNGTRANSFORMINVERTALPHA  Change alpha from opacity\nto transparency\nPNGTRANSFORMSWAPENDIAN   Byte-swap 16-bit samples\nPNGTRANSFORMGRAYTORGB   Expand grayscale samples\nto RGB (or GA to RGBA)\nPNGTRANSFORMEXPAND16     Expand samples to 16 bits\n\n(This  excludes  setting a background color, doing gamma transformation, quantizing, and set‐\nting filler.)  If this is the case, simply do this:\n\npngreadpng(pngptr, infoptr, pngtransforms, NULL)\n\nwhere pngtransforms is an integer containing the bitwise OR of some  set  of  transformation\nflags.  This call is equivalent to pngreadinfo(), followed the set of transformations indi‐\ncated by the transform mask, then pngreadimage(), and finally pngreadend().\n\n(The  final parameter of this call is not yet used.  Someday it might point to transformation\nparameters required by some future input transform.)\n\nYou must use pngtransforms and not call  any  pngsettransform()  functions  when  you  use\npngreadpng().\n\nAfter you have called pngreadpng(), you can retrieve the image data with\n\nrowpointers = pnggetrows(pngptr, infoptr);\n\nwhere rowpointers is an array of pointers to the pixel data for each row:\n\npngbytep rowpointers[height];\n\nIf you know your image size and pixel size ahead of time, you can allocate rowpointers prior\nto calling pngreadpng() with\n\nif (height > PNGUINT32MAX / (sizeof (pngbytep)))\npngerror(pngptr,\n\"Image is too tall to process in memory\");\n\nif (width > PNGUINT32MAX / pixelsize)\npngerror(pngptr,\n\"Image is too wide to process in memory\");\n\nrowpointers = pngmalloc(pngptr,\nheight*(sizeof (pngbytep)));\n\nfor (int i = 0; i < height, i++)\nrowpointers[i] = NULL;  /* security precaution */\n\nfor (int i = 0; i < height, i++)\nrowpointers[i] = pngmalloc(pngptr,\nwidth*pixelsize);\n\npngsetrows(pngptr, infoptr, &rowpointers);\n\nAlternatively  you  could  allocate your image in one big block and define rowpointers[i] to\npoint into the proper places in your block, but first be sure that your platform is  able  to\nallocate such a large buffer:\n\n/* Guard against integer overflow */\nif (height > PNGSIZEMAX/(width*pixelsize))\npngerror(pngptr, \"imagedata buffer would be too large\");\n\npngbytep buffer = pngmalloc(pngptr,\nheight*width*pixelsize);\n\nfor (int i = 0; i < height, i++)\nrowpointers[i] = buffer + i*width*pixelsize;\n\npngsetrows(pngptr, infoptr, &rowpointers);\n\nIf  you  use  pngsetrows(),  the  application  is responsible for freeing rowpointers (and\nrowpointers[i], if they were separately allocated).\n\nIf you don't allocate rowpointers ahead of time, pngreadpng() will do  it,  and  it'll  be\nfree'ed by libpng when you call pngdestroy*().\n\n"
                },
                {
                    "name": "The low-level read interface",
                    "content": "If  you  are going the low-level route, you are now ready to read all the file information up\nto the actual image data.  You do this with a call to pngreadinfo().\n\npngreadinfo(pngptr, infoptr);\n\nThis will process all chunks up to but not including the image data.\n\nThis also copies some of the data from the PNG file into the  decode  structure  for  use  in\nlater transformations.  Important information copied in is:\n\n1)  The PNG file gamma from the gAMA chunk.  This overwrites the default value provided by an\nearlier call to pngsetgamma or pngsetalphamode.\n\n2) Prior to libpng-1.5.4 the background color from a bKGd chunk.  This damages  the  informa‐\ntion  provided  by  an  earlier  call to pngsetbackground resulting in unexpected behavior.\nLibpng-1.5.4 no longer does this.\n\n3) The number of significant bits in each component value.   Libpng  uses  this  to  optimize\ngamma handling by reducing the internal lookup table sizes.\n\n4) The transparent color information from a tRNS chunk.  This can be modified by a later call\nto pngsettRNS.\n\n"
                },
                {
                    "name": "Querying the info structure",
                    "content": "Functions are used to get the information from the infoptr once it has been read.  Note that\nthese  fields  may  not  be completely filled in until pngreadend() has read the chunk data\nfollowing the image.\n\npnggetIHDR(pngptr, infoptr, &width, &height,\n&bitdepth, &colortype, &interlacetype,\n&compressiontype, &filtermethod);\n\nwidth          - holds the width of the image\nin pixels (up to 2^31).\n\nheight         - holds the height of the image\nin pixels (up to 2^31).\n\nbitdepth      - holds the bit depth of one of the\nimage channels.  (valid values are\n1, 2, 4, 8, 16 and depend also on\nthe colortype.  See also\nsignificant bits (sBIT) below).\n\ncolortype     - describes which color/alpha channels\nare present.\nPNGCOLORTYPEGRAY\n(bit depths 1, 2, 4, 8, 16)\nPNGCOLORTYPEGRAYALPHA\n(bit depths 8, 16)\nPNGCOLORTYPEPALETTE\n(bit depths 1, 2, 4, 8)\nPNGCOLORTYPERGB\n(bitdepths 8, 16)\nPNGCOLORTYPERGBALPHA\n(bitdepths 8, 16)\n\nPNGCOLORMASKPALETTE\nPNGCOLORMASKCOLOR\nPNGCOLORMASKALPHA\n\ninterlacetype - (PNGINTERLACENONE or\nPNGINTERLACEADAM7)\n\ncompressiontype - (must be PNGCOMPRESSIONTYPEBASE\nfor PNG 1.0)\n\nfiltermethod  - (must be PNGFILTERTYPEBASE\nfor PNG 1.0, and can also be\nPNGINTRAPIXELDIFFERENCING if\nthe PNG datastream is embedded in\na MNG-1.0 datastream)\n\nAny of width, height, colortype, bitdepth,\ninterlacetype, compressiontype, or filtermethod can\nbe NULL if you are not interested in their values.\n\nNote that pnggetIHDR() returns 32-bit data into\nthe application's width and height variables.\nThis is an unsafe situation if these are not pnguint32\nvariables.  In such situations, the\npnggetimagewidth() and pnggetimageheight()\nfunctions described below are safer.\n\nwidth            = pnggetimagewidth(pngptr,\ninfoptr);\n\nheight           = pnggetimageheight(pngptr,\ninfoptr);\n\nbitdepth        = pnggetbitdepth(pngptr,\ninfoptr);\n\ncolortype       = pnggetcolortype(pngptr,\ninfoptr);\n\ninterlacetype   = pnggetinterlacetype(pngptr,\ninfoptr);\n\ncompressiontype = pnggetcompressiontype(pngptr,\ninfoptr);\n\nfiltermethod    = pnggetfiltertype(pngptr,\ninfoptr);\n\nchannels = pnggetchannels(pngptr, infoptr);\n\nchannels       - number of channels of info for the\ncolor type (valid values are 1 (GRAY,\nPALETTE), 2 (GRAYALPHA), 3 (RGB),\n4 (RGBALPHA or RGB + filler byte))\n\nrowbytes = pnggetrowbytes(pngptr, infoptr);\n\nrowbytes       - number of bytes needed to hold a row\nThis value, the bitdepth, colortype,\nand the number of channels can change\nif you use transforms such as\npngsetexpand(). See\npngreadupdateinfo(), below.\n\nsignature = pnggetsignature(pngptr, infoptr);\n\nsignature      - holds the signature read from the\nfile (if any).  The data is kept in\nthe same offset it would be if the\nwhole signature were read (i.e. if an\napplication had already read in 4\nbytes of signature before starting\nlibpng, the remaining 4 bytes would\nbe in signature[4] through signature[7]\n(see pngsetsigbytes())).\n\nThese are also important, but their validity depends on whether the chunk has been read.  The\npnggetvalid(pngptr, infoptr,  PNGINFO<chunk>)  and  pngget<chunk>(pngptr,  infoptr,\n...)  functions return non-zero if the data has been read, or zero if it is missing.  The pa‐\nrameters to the pngget<chunk> are set directly if they are simple data types, or a  pointer\ninto the infoptr is returned for any complex types.\n\nThe  colorspace  data from gAMA, cHRM, sRGB, iCCP, and sBIT chunks is simply returned to give\nthe application information about how the image was encoded.  Libpng itself only does  trans‐\nformations  using  the  file  gamma when combining semitransparent pixels with the background\ncolor, and, since libpng-1.6.0, when converting between 8-bit sRGB and 16-bit  linear  pixels\nwithin  the simplified API.  Libpng also uses the file gamma when converting RGB to gray, be‐\nginning with libpng-1.0.5, if the application calls pngsetrgbtogray()).\n\npnggetPLTE(pngptr, infoptr, &palette,\n&numpalette);\n\npalette        - the palette for the file\n(array of pngcolor)\n\nnumpalette    - number of entries in the palette\n\npnggetgAMA(pngptr, infoptr, &filegamma);\npnggetgAMAfixed(pngptr, infoptr, &intfilegamma);\n\nfilegamma     - the gamma at which the file is\nwritten (PNGINFOgAMA)\n\nintfilegamma - 100,000 times the gamma at which the\nfile is written\n\npnggetcHRM(pngptr, infoptr,  &whitex, &whitey, &redx,\n&redy, &greenx, &greeny, &bluex, &bluey)\npnggetcHRMXYZ(pngptr, infoptr, &redX, &redY, &redZ,\n&greenX, &greenY, &greenZ, &blueX, &blueY,\n&blueZ)\npnggetcHRMfixed(pngptr, infoptr, &intwhitex,\n&intwhitey, &intredx, &intredy,\n&intgreenx, &intgreeny, &intbluex,\n&intbluey)\npnggetcHRMXYZfixed(pngptr, infoptr, &intredX, &intredY,\n&intredZ, &intgreenX, &intgreenY,\n&intgreenZ, &intblueX, &intblueY,\n&intblueZ)\n\n{white,red,green,blue}{x,y}\nA color space encoding specified using the\nchromaticities of the end points and the\nwhite point. (PNGINFOcHRM)\n\n{red,green,blue}{X,Y,Z}\nA color space encoding specified using the\nencoding end points - the CIE tristimulus\nspecification of the intended color of the red,\ngreen and blue channels in the PNG RGB data.\nThe white point is simply the sum of the three\nend points. (PNGINFOcHRM)\n\npnggetsRGB(pngptr, infoptr, &srgbintent);\n\nsrgbintent -    the rendering intent (PNGINFOsRGB)\nThe presence of the sRGB chunk\nmeans that the pixel data is in the\nsRGB color space.  This chunk also\nimplies specific values of gAMA and\ncHRM.\n\npnggetiCCP(pngptr, infoptr, &name,\n&compressiontype, &profile, &proflen);\n\nname             - The profile name.\n\ncompressiontype - The compression type; always\nPNGCOMPRESSIONTYPEBASE for PNG 1.0.\nYou may give NULL to this argument to\nignore it.\n\nprofile          - International Color Consortium color\nprofile data. May contain NULs.\n\nproflen          - length of profile data in bytes.\n\npnggetsBIT(pngptr, infoptr, &sigbit);\n\nsigbit        - the number of significant bits for\n(PNGINFOsBIT) each of the gray,\nred, green, and blue channels,\nwhichever are appropriate for the\ngiven color type (pngcolor16)\n\npnggettRNS(pngptr, infoptr, &transalpha,\n&numtrans, &transcolor);\n\ntransalpha    - array of alpha (transparency)\nentries for palette (PNGINFOtRNS)\n\nnumtrans      - number of transparent entries\n(PNGINFOtRNS)\n\ntranscolor    - graylevel or color sample values of\nthe single transparent color for\nnon-paletted images (PNGINFOtRNS)\n\npnggeteXIf1(pngptr, infoptr, &numexif, &exif);\n\nexif           - Exif profile (array of pngbyte)\n(PNGINFOeXIf)\n\npnggethIST(pngptr, infoptr, &hist);\n\nhist           - histogram of palette (array of\npnguint16) (PNGINFOhIST)\n\npnggettIME(pngptr, infoptr, &modtime);\n\nmodtime       - time image was last modified\n(PNGINFOtIME)\n\npnggetbKGD(pngptr, infoptr, &background);\n\nbackground     - background color (of type\npngcolor16p) (PNGINFObKGD)\nvalid 16-bit red, green and blue\nvalues, regardless of colortype\n\nnumcomments   = pnggettext(pngptr, infoptr,\n&textptr, &numtext);\n\nnumcomments   - number of comments\n\ntextptr       - array of pngtext holding image\ncomments\n\ntextptr[i].compression - type of compression used\non \"text\" PNGTEXTCOMPRESSIONNONE\nPNGTEXTCOMPRESSIONzTXt\nPNGITXTCOMPRESSIONNONE\nPNGITXTCOMPRESSIONzTXt\n\ntextptr[i].key   - keyword for comment.  Must contain\n1-79 characters.\n\ntextptr[i].text  - text comments for current\nkeyword.  Can be empty.\n\ntextptr[i].textlength - length of text string,\nafter decompression, 0 for iTXt\n\ntextptr[i].itxtlength - length of itxt string,\nafter decompression, 0 for tEXt/zTXt\n\ntextptr[i].lang  - language of comment (empty\nstring for unknown).\n\ntextptr[i].langkey  - keyword in UTF-8\n(empty string for unknown).\n\nNote that the itxtlength, lang, and langkey\nmembers of the textptr structure only exist when the\nlibrary is built with iTXt chunk support.  Prior to\nlibpng-1.4.0 the library was built by default without\niTXt support. Also note that when iTXt is supported,\nthey contain NULL pointers when the \"compression\"\nfield contains PNGTEXTCOMPRESSIONNONE or\nPNGTEXTCOMPRESSIONzTXt.\n\nnumtext       - number of comments (same as\nnumcomments; you can put NULL here\nto avoid the duplication)\n\nNote while pngsettext() will accept text, language,\nand translated keywords that can be NULL pointers, the\nstructure returned by pnggettext will always contain\nregular zero-terminated C strings.  They might be\nempty strings but they will never be NULL pointers.\n\nnumspalettes = pnggetsPLT(pngptr, infoptr,\n&paletteptr);\n\nnumspalettes  - number of sPLT chunks read.\n\npaletteptr    - array of palette structures holding\ncontents of one or more sPLT chunks\nread.\n\npnggetoFFs(pngptr, infoptr, &offsetx, &offsety,\n&unittype);\n\noffsetx       - positive offset from the left edge\nof the screen (can be negative)\n\noffsety       - positive offset from the top edge\nof the screen (can be negative)\n\nunittype      - PNGOFFSETPIXEL, PNGOFFSETMICROMETER\n\npnggetpHYs(pngptr, infoptr, &resx, &resy,\n&unittype);\n\nresx          - pixels/unit physical resolution in\nx direction\n\nresy          - pixels/unit physical resolution in\nx direction\n\nunittype      - PNGRESOLUTIONUNKNOWN,\nPNGRESOLUTIONMETER\n\npnggetsCAL(pngptr, infoptr, &unit, &width,\n&height)\n\nunit        - physical scale units (an integer)\n\nwidth       - width of a pixel in physical scale units\n\nheight      - height of a pixel in physical scale units\n(width and height are doubles)\n\npnggetsCALs(pngptr, infoptr, &unit, &width,\n&height)\n\nunit        - physical scale units (an integer)\n\nwidth       - width of a pixel in physical scale units\n(expressed as a string)\n\nheight      - height of a pixel in physical scale units\n(width and height are strings like \"2.54\")\n\nnumunknownchunks = pnggetunknownchunks(pngptr,\ninfoptr, &unknowns)\n\nunknowns          - array of pngunknownchunk\nstructures holding unknown chunks\n\nunknowns[i].name  - name of unknown chunk\n\nunknowns[i].data  - data of unknown chunk\n\nunknowns[i].size  - size of unknown chunk's data\n\nunknowns[i].location - position of chunk in file\n\nThe value of \"i\" corresponds to the order in which the\nchunks were read from the PNG file or inserted with the\npngsetunknownchunks() function.\n\nThe value of \"location\" is a bitwise \"or\" of\n\nPNGHAVEIHDR  (0x01)\nPNGHAVEPLTE  (0x02)\nPNGAFTERIDAT (0x08)\n\nThe data from the pHYs chunk can be retrieved in several convenient forms:\n\nresx = pnggetxpixelspermeter(pngptr,\ninfoptr)\n\nresy = pnggetypixelspermeter(pngptr,\ninfoptr)\n\nresxandy = pnggetpixelspermeter(pngptr,\ninfoptr)\n\nresx = pnggetxpixelsperinch(pngptr,\ninfoptr)\n\nresy = pnggetypixelsperinch(pngptr,\ninfoptr)\n\nresxandy = pnggetpixelsperinch(pngptr,\ninfoptr)\n\naspectratio = pnggetpixelaspectratio(pngptr,\ninfoptr)\n\nEach of these returns 0 [signifying \"unknown\"] if\nthe data is not present or if resx is 0;\nresxandy is 0 if resx != resy\n\nNote that because of the way the resolutions are\nstored internally, the inch conversions won't\ncome out to exactly even number.  For example,\n72 dpi is stored as 0.28346 pixels/meter, and\nwhen this is retrieved it is 71.9988 dpi, so\nbe sure to round the returned value appropriately\nif you want to display a reasonable-looking result.\n\nThe data from the oFFs chunk can be retrieved in several convenient forms:\n\nxoffset = pnggetxoffsetmicrons(pngptr, infoptr);\n\nyoffset = pnggetyoffsetmicrons(pngptr, infoptr);\n\nxoffset = pnggetxoffsetinches(pngptr, infoptr);\n\nyoffset = pnggetyoffsetinches(pngptr, infoptr);\n\nEach of these returns 0 [signifying \"unknown\" if both\nx and y are 0] if the data is not present or if the\nchunk is present but the unit is the pixel.  The\nremark about inexact inch conversions applies here\nas well, because a value in inches can't always be\nconverted to microns and back without some loss\nof precision.\n\nFor more information, see the PNG specification for chunk contents.  Be careful with trusting\nrowbytes, as some of the transformations could increase the space needed to hold a  row  (ex‐\npand, filler, graytorgb, etc.).  See pngreadupdateinfo(), below.\n\nA  quick  word  about  textptr and numtext.  PNG stores comments in keyword/text pairs, one\npair per chunk, with no limit on the number of text chunks, and a 2^31 byte  limit  on  their\nsize.   While  there  are  suggested keywords, there is no requirement to restrict the use to\nthese strings.  It is strongly suggested that keywords and text be sensible to humans (that's\nthe point), so don't use abbreviations.  Non-printing symbols are not allowed.  See  the  PNG\nspecification for more details.  There is also no requirement to have text after the keyword.\n\nKeywords  should  be limited to 79 Latin-1 characters without leading or trailing spaces, but\nnon-consecutive spaces are allowed within the keyword.  It is possible to have the same  key‐\nword  any  number  of times.  The textptr is an array of pngtext structures, each holding a\npointer to a language string, a pointer to a keyword and a pointer to  a  text  string.   The\ntext  string,  language code, and translated keyword may be empty or NULL pointers.  The key‐\nword/text pairs are put into the array in the order that they are received.  However, some or\nall of the text chunks may be after the image, so, to make sure you have read  all  the  text\nchunks,  don't  mess with these until after you read the stuff after the image.  This will be\nmentioned again below in the discussion that goes with pngreadend().\n\n"
                },
                {
                    "name": "Input transformations",
                    "content": "After you've read the header information, you can set up the library to  handle  any  special\ntransformations  of the image data.  The various ways to transform the data will be described\nin the order that they should occur.  This is important, as some of these  change  the  color\ntype  and/or  bit depth of the data, and some others only work on certain color types and bit\ndepths.\n\nTransformations you request are ignored if they don't have any meaning for a particular input\ndata format.  However some transformations can have an effect  as  a  result  of  a  previous\ntransformation.   If  you  specify  a  contradictory set of transformations, for example both\nadding and removing the alpha channel, you cannot predict the final result.\n\nThe color used for the transparency values should be supplied in the same format/depth as the\ncurrent image data.  It is stored in the same format/depth as the image data in a tRNS chunk,\nso this is what libpng expects for this data.\n\nThe color used for the background value depends on the needexpand argument as described  be‐\nlow.\n\nData  will  be decoded into the supplied row buffers packed into bytes unless the library has\nbeen told to transform it  into  another  format.   For  example,  4  bit/pixel  paletted  or\ngrayscale  data will be returned 2 pixels/byte with the leftmost pixel in the high-order bits\nof the byte, unless pngsetpacking() is called.  8-bit RGB data will be stored  in  RGB  RGB\nRGB  format  unless pngsetfiller() or pngsetaddalpha() is called to insert filler bytes,\neither before or after each RGB triplet.\n\n16-bit RGB data will be returned RRGGBB RRGGBB, with the most significant byte of  the  color\nvalue first, unless pngsetscale16() is called to transform it to regular RGB RGB triplets,\nor  pngsetfiller()  or pngsetadd alpha() is called to insert two filler bytes, either be‐\nfore or after each RRGGBB triplet.  Similarly, 8-bit or 16-bit grayscale data can be modified\nwith pngsetfiller(), pngsetaddalpha(), pngsetstrip16(), or pngsetscale16().\n\nThe following code transforms grayscale images of less than 8 to 8 bits, changes paletted im‐\nages to RGB, and adds a full alpha channel if there is transparency  information  in  a  tRNS\nchunk.   This  is  most useful on grayscale images with bit depths of 2 or 4 or if there is a\nmultiple-image viewing application that wishes to treat all images in the same way.\n\nif (colortype == PNGCOLORTYPEPALETTE)\npngsetpalettetorgb(pngptr);\n\nif (pnggetvalid(pngptr, infoptr, PNGINFOtRNS))\npngsettRNStoalpha(pngptr);\n\nif (colortype == PNGCOLORTYPEGRAY && bitdepth < 8)\npngsetexpandgray124to8(pngptr);\n\nThe first two functions are actually aliases for pngsetexpand(), added  in  libpng  version\n1.0.4,  with the function names expanded to improve code readability.  In some future version\nthey may actually do different things.\n\nAs of libpng version 1.2.9, pngsetexpandgray124to8() was added.  It expands the  sam‐\nple depth without changing tRNS to alpha.\n\nAs  of  libpng version 1.5.2, pngsetexpand16() was added.  It behaves as pngsetexpand();\nhowever, the resultant channels have 16 bits rather than 8.  Use this when the  output  color\nor gray channels are made linear to avoid fairly severe accuracy loss.\n\nif (bitdepth < 16)\npngsetexpand16(pngptr);\n\nPNG can have files with 16 bits per channel.  If you only can handle 8 bits per channel, this\nwill strip the pixels down to 8-bit.\n\nif (bitdepth == 16)\n{ #if PNGLIBPNGVER >= 10504\npngsetscale16(pngptr); #else\npngsetstrip16(pngptr); #endif\n}\n\n(The more accurate \"pngsetscale16()\" API became available in libpng version 1.5.4).\n\nIf you need to process the alpha channel on the image separately from the image data (for ex‐\nample  if  you  convert  it to a bitmap mask) it is possible to have libpng strip the channel\nleaving just RGB or gray data:\n\nif (colortype & PNGCOLORMASKALPHA)\npngsetstripalpha(pngptr);\n\nIf you strip the alpha channel you need to find some other way of dealing with  the  informa‐\ntion.   If, instead, you want to convert the image to an opaque version with no alpha channel\nuse pngsetbackground; see below.\n\nAs of libpng version 1.5.2, almost all useful expansions are supported, the  major  omissions\nare  conversion  of  grayscale to indexed images (which can be done trivially in the applica‐\ntion) and conversion of indexed to grayscale (which can be done by a trivial manipulation  of\nthe palette.)\n\nIn  the  following table, the 01 means grayscale with depth<8, 31 means indexed with depth<8,\nother numerals represent the color type, \"T\" means the tRNS chunk is present, A means an  al‐\npha  channel is present, and O means tRNS or alpha is present but all pixels in the image are\nopaque.\n\nFROM  01  31   0  0T  0O   2  2T  2O   3  3T  3O  4A  4O  6A  6O\nTO\n01    -  [G]  -   -   -   -   -   -   -   -   -   -   -   -   -\n31   [Q]  Q  [Q] [Q] [Q]  Q   Q   Q   Q   Q   Q  [Q] [Q]  Q   Q\n0    1   G   +   .   .   G   G   G   G   G   G   B   B  GB  GB\n0T    lt  Gt  t   +   .   Gt  G   G   Gt  G   G   Bt  Bt GBt GBt\n0O    lt  Gt  t   .   +   Gt  Gt  G   Gt  Gt  G   Bt  Bt GBt GBt\n2    C   P   C   C   C   +   .   .   C   -   -  CB  CB   B   B\n2T    Ct  -   Ct  C   C   t   +   t   -   -   -  CBt CBt  Bt  Bt\n2O    Ct  -   Ct  C   C   t   t   +   -   -   -  CBt CBt  Bt  Bt\n3   [Q]  p  [Q] [Q] [Q]  Q   Q   Q   +   .   .  [Q] [Q]  Q   Q\n3T   [Qt] p  [Qt][Q] [Q]  Qt  Qt  Qt  t   +   t  [Qt][Qt] Qt  Qt\n3O   [Qt] p  [Qt][Q] [Q]  Qt  Qt  Qt  t   t   +  [Qt][Qt] Qt  Qt\n4A    lA  G   A   T   T   GA  GT  GT  GA  GT  GT  +   BA  G  GBA\n4O    lA GBA  A   T   T   GA  GT  GT  GA  GT  GT  BA  +  GBA  G\n6A    CA  PA  CA  C   C   A   T  tT   PA  P   P   C  CBA  +   BA\n6O    CA PBA  CA  C   C   A  tT   T   PA  P   P  CBA  C   BA  +\n\nWithin the matrix,\n\"+\" identifies entries where 'from' and 'to' are the same.\n\"-\" means the transformation is not supported.\n\".\" means nothing is necessary (a tRNS chunk can just be ignored).\n\"t\" means the transformation is obtained by pngsettRNS.\n\"A\" means the transformation is obtained by pngsetaddalpha().\n\"X\" means the transformation is obtained by pngsetexpand().\n\"1\" means the transformation is obtained by\npngsetexpandgray124to8() (and by pngsetexpand()\nif there is no transparency in the original or the final\nformat).\n\"C\" means the transformation is obtained by pngsetgraytorgb().\n\"G\" means the transformation is obtained by pngsetrgbtogray().\n\"P\" means the transformation is obtained by\npngsetexpandpalettetorgb().\n\"p\" means the transformation is obtained by pngsetpacking().\n\"Q\" means the transformation is obtained by pngsetquantize().\n\"T\" means the transformation is obtained by\npngsettRNStoalpha().\n\"B\" means the transformation is obtained by\npngsetbackground(), or pngstripalpha().\n\nWhen an entry has multiple transforms listed all are required  to  cause  the  right  overall\ntransformation.   When  two transforms are separated by a comma either will do the job.  When\ntransforms are enclosed in [] the transform should do the job but this is currently  unimple‐\nmented - a different format will result if the suggested transformations are used.\n\nIn  PNG  files, the alpha channel in an image is the level of opacity.  If you need the alpha\nchannel in an image to be the level of transparency instead of opacity, you  can  invert  the\nalpha channel (or the tRNS chunk data) after it's read, so that 0 is fully opaque and 255 (in\n8-bit or paletted images) or 65535 (in 16-bit images) is fully transparent, with\n\npngsetinvertalpha(pngptr);\n\nPNG  files  pack  pixels of bit depths 1, 2, and 4 into bytes as small as they can, resulting\nin, for example, 8 pixels per byte for 1 bit files.  This code expands to 1  pixel  per  byte\nwithout changing the values of the pixels:\n\nif (bitdepth < 8)\npngsetpacking(pngptr);\n\nPNG  files  have possible bit depths of 1, 2, 4, 8, and 16.  All pixels stored in a PNG image\nhave been \"scaled\" or \"shifted\" up to the  next  higher  possible  bit  depth  (e.g.  from  5\nbits/sample in the range [0,31] to 8 bits/sample in the range [0, 255]).  However, it is also\npossible  to  convert  the  PNG pixel data back to the original bit depth of the image.  This\ncall reduces the pixels back down to the original bit depth:\n\npngcolor8p sigbit;\n\nif (pnggetsBIT(pngptr, infoptr, &sigbit))\npngsetshift(pngptr, sigbit);\n\nPNG files store 3-color pixels in red, green, blue order.  This code changes the  storage  of\nthe pixels to blue, green, red:\n\nif (colortype == PNGCOLORTYPERGB ||\ncolortype == PNGCOLORTYPERGBALPHA)\npngsetbgr(pngptr);\n\nPNG files store RGB pixels packed into 3 or 6 bytes. This code expands them into 4 or 8 bytes\nfor windowing systems that need them in this format:\n\nif (colortype == PNGCOLORTYPERGB)\npngsetfiller(pngptr, filler, PNGFILLERBEFORE);\n\nwhere  \"filler\"  is  the  8-bit  or  16-bit  number  to fill with, and the location is either\nPNGFILLERBEFORE or PNGFILLERAFTER, depending upon whether you want the filler before  the\nRGB  or  after.  When  filling an 8-bit pixel, the least significant 8 bits of the number are\nused, if a 16-bit number is supplied.  This transformation does not affect  images  that  al‐\nready  have  full  alpha  channels.   To  add  an opaque alpha channel, use filler=0xffff and\nPNGFILLERAFTER which will generate RGBA pixels.\n\nNote that pngsetfiller() does not change the color type.  If you want to do that,  you  can\nadd a true alpha channel with\n\nif (colortype == PNGCOLORTYPERGB ||\ncolortype == PNGCOLORTYPEGRAY)\npngsetaddalpha(pngptr, filler, PNGFILLERAFTER);\n\nwhere  \"filler\"  contains  the  alpha value to assign to each pixel.  The pngsetaddalpha()\nfunction was added in libpng-1.2.7.\n\nIf you are reading an image with an alpha channel, and you need the data as ARGB  instead  of\nthe normal PNG format RGBA:\n\nif (colortype == PNGCOLORTYPERGBALPHA)\npngsetswapalpha(pngptr);\n\nFor  some  uses,  you may want a grayscale image to be represented as RGB.  This code will do\nthat conversion:\n\nif (colortype == PNGCOLORTYPEGRAY ||\ncolortype == PNGCOLORTYPEGRAYALPHA)\npngsetgraytorgb(pngptr);\n\nConversely, you can convert an RGB or RGBA image to grayscale or grayscale with alpha.\n\nif (colortype == PNGCOLORTYPERGB ||\ncolortype == PNGCOLORTYPERGBALPHA)\npngsetrgbtogray(pngptr, erroraction,\n(double)redweight, (double)greenweight);\n\nerroraction = 1: silently do the conversion\n\nerroraction = 2: issue a warning if the original\nimage has any pixel where\nred != green or red != blue\n\nerroraction = 3: issue an error and abort the\nconversion if the original\nimage has any pixel where\nred != green or red != blue\n\nredweight:       weight of red component\n\ngreenweight:     weight of green component\nIf either weight is negative, default\nweights are used.\n\nIn the corresponding fixed point API the redweight and greenweight values are simply scaled\nby 100,000:\n\npngsetrgbtogray(pngptr, erroraction,\n(pngfixedpoint)redweight,\n(pngfixedpoint)greenweight);\n\nIf you have set erroraction = 1 or 2, you can later check whether the image really was gray,\nafter processing the image rows, with the pnggetrgbtograystatus(pngptr)  function.   It\nwill  return  a  pngbyte  that is zero if the image was gray or 1 if there were any non-gray\npixels.  Background and sBIT data will be silently converted to grayscale,  using  the  green\nchannel data for sBIT, regardless of the erroraction setting.\n\nThe default values come from the PNG file cHRM chunk if present; otherwise, the defaults cor‐\nrespond to the ITU-R recommendation 709, and also the sRGB color space, as recommended in the\nCharles Poynton's Colour FAQ, Copyright (c) 2006-11-28 Charles Poynton, in section 9:\n\n<http://www.poynton.com/notes/colourandgamma/ColorFAQ.html#RTFToC9>\n\nY = 0.2126 * R + 0.7152 * G + 0.0722 * B\n\nPrevious  versions of this document, 1998 through 2002, recommended a slightly different for‐\nmula:\n\nY = 0.212671 * R + 0.715160 * G + 0.072169 * B\n\nLibpng uses an integer approximation:\n\nY = (6968 * R + 23434 * G + 2366 * B)/32768\n\nThe calculation is done in a linear colorspace, if the image gamma can be determined.\n\nThe pngsetbackground() function has been described already; it tells  libpng  to  composite\nimages with alpha or simple transparency against the supplied background color.  For compati‐\nbility  with versions of libpng earlier than libpng-1.5.4 it is recommended that you call the\nfunction after reading the file header, even if you don't want to use the  color  in  a  bKGD\nchunk, if one exists.\n\nIf  the PNG file contains a bKGD chunk (PNGINFObKGD valid), you may use this color, or sup‐\nply another color more suitable for the current display (e.g., the background  color  from  a\nweb page).  You need to tell libpng how the color is represented, both the format of the com‐\nponent  values  in  the  color (the number of bits) and the gamma encoding of the color.  The\nfunction takes two arguments, backgroundgammamode and needexpand to convey  this  informa‐\ntion; however, only two combinations are likely to be useful:\n\npngcolor16 mybackground;\npngcolor16p imagebackground;\n\nif (pnggetbKGD(pngptr, infoptr, &imagebackground))\npngsetbackground(pngptr, imagebackground,\nPNGBACKGROUNDGAMMAFILE, 1/*needs to be expanded*/, 1);\nelse\npngsetbackground(pngptr, &mybackground,\nPNGBACKGROUNDGAMMASCREEN, 0/*do not expand*/, 1);\n\nThe  second  call was described above - mybackground is in the format of the final, display,\noutput produced by libpng.  Because you now know the format of the  PNG  it  is  possible  to\navoid  the  need  to  choose  either 8-bit or 16-bit output and to retain palette images (the\npalette colors will be modified appropriately and the tRNS chunk removed.)  However,  if  you\nare  doing  this,  take great care not to ask for transformations without checking first that\nthey apply!\n\nIn the first call the background color has the original bit depth and color type of  the  PNG\nfile.   So,  for  palette  images  the  color  is supplied as a palette index and for low bit\ngreyscale images the color is a reduced bit value in imagebackground->gray.\n\nIf you didn't call pngsetgamma() before reading the file header, for example  if  you  need\nyour  code  to remain compatible with older versions of libpng prior to libpng-1.5.4, this is\nthe place to call it.\n\nDo not call it if you called pngsetalphamode(); doing so will damage the settings  put  in\nplace  by pngsetalphamode().  (If pngsetalphamode() is supported then you can certainly\ndo pngsetgamma() before reading the PNG header.)\n\nThis API unconditionally sets the screen and file gamma values, so it will override the value\nin the PNG file unless it is called before the PNG file reading starts.  For this reason  you\nmust always call it with the PNG file value when you call it in this position:\n\nif (pnggetgAMA(pngptr, infoptr, &filegamma))\npngsetgamma(pngptr, screengamma, filegamma);\n\nelse\npngsetgamma(pngptr, screengamma, 0.45455);\n\nIf  you need to reduce an RGB file to a paletted file, or if a paletted file has more entries\nthan will fit on your screen, pngsetquantize() will do that.  Note that this  is  a  simple\nmatch  quantization  that  merely finds the closest color available.  This should work fairly\nwell with optimized palettes, but fairly badly with  linear  color  cubes.   If  you  pass  a\npalette  that is larger than maximumcolors, the file will reduce the number of colors in the\npalette so it will fit into maximumcolors.  If there is a histogram, libpng will use  it  to\nmake  more  intelligent  choices when reducing the palette.  If there is no histogram, it may\nnot do as good a job.\n\nif (colortype & PNGCOLORMASKCOLOR)\n{\nif (pnggetvalid(pngptr, infoptr,\nPNGINFOPLTE))\n{\npnguint16p histogram = NULL;\n\npnggethIST(pngptr, infoptr,\n&histogram);\npngsetquantize(pngptr, palette, numpalette,\nmaxscreencolors, histogram, 1);\n}\n\nelse\n{\npngcolor stdcolorcube[MAXSCREENCOLORS] =\n{ ... colors ... };\n\npngsetquantize(pngptr, stdcolorcube,\nMAXSCREENCOLORS, MAXSCREENCOLORS,\nNULL,0);\n}\n}\n\nPNG files describe monochrome as black being zero and white being one.   The  following  code\nwill reverse this (make black be one and white be zero):\n\nif (bitdepth == 1 && colortype == PNGCOLORTYPEGRAY)\npngsetinvertmono(pngptr);\n\nThis function can also be used to invert grayscale and gray-alpha images:\n\nif (colortype == PNGCOLORTYPEGRAY ||\ncolortype == PNGCOLORTYPEGRAYALPHA)\npngsetinvertmono(pngptr);\n\nPNG  files  store  16-bit pixels in network byte order (big-endian, ie. most significant bits\nfirst).  This code changes the storage to the other way (little-endian, i.e.  least  signifi‐\ncant bits first, the way PCs store them):\n\nif (bitdepth == 16)\npngsetswap(pngptr);\n\nIf  you are using packed-pixel images (1, 2, or 4 bits/pixel), and you need to change the or‐\nder the pixels are packed into bytes, you can use:\n\nif (bitdepth < 8)\npngsetpackswap(pngptr);\n\nFinally, you can write your own transformation function if none of the  existing  ones  meets\nyour needs.  This is done by setting a callback with\n\npngsetreadusertransformfn(pngptr,\nreadtransformfn);\n\nYou must supply the function\n\nvoid readtransformfn(pngstructp pngptr, pngrowinfop\nrowinfo, pngbytep data)\n\nSee  pngtest.c  for  a  working example.  Your function will be called after all of the other\ntransformations have been processed.  Take care with interlaced images if you do  the  inter‐\nlace yourself - the width of the row is the width in 'rowinfo', not the overall image width.\n\nIf supported, libpng provides two information routines that you can use to find where you are\nin processing the image:\n\npnggetcurrentpassnumber(pngstructp pngptr);\npnggetcurrentrownumber(pngstructp pngptr);\n\nDon't  try using these outside a transform callback - firstly they are only supported if user\ntransforms are supported, secondly they may well return unexpected results unless the row  is\nactually being processed at the moment they are called.\n\nWith  interlaced  images  the  value  returned  is the row in the input sub-image image.  Use\nPNGROWFROMPASSROW(row, pass) and PNGCOLFROMPASSCOL(col,  pass)  to  find  the  output\npixel (x,y) given an interlaced sub-image pixel (row,col,pass).\n\nThe discussion of interlace handling above contains more information on how to use these val‐\nues.\n\nYou  can also set up a pointer to a user structure for use by your callback function, and you\ncan inform libpng that your transform function will change the  number  of  channels  or  bit\ndepth with the function\n\npngsetusertransforminfo(pngptr, userptr,\nuserdepth, userchannels);\n\nThe  user's application, not libpng, is responsible for allocating and freeing any memory re‐\nquired for the user structure.\n\nYou can retrieve the pointer via the function pnggetusertransformptr().  For example:\n\nvoidp readusertransformptr =\npnggetusertransformptr(pngptr);\n\nThe last thing to handle is interlacing; this is covered in detail below, but you  must  call\nthe function here if you want libpng to handle expansion of the interlaced image.\n\nnumberofpasses = pngsetinterlacehandling(pngptr);\n\nAfter  setting  the transformations, libpng can update your pnginfo structure to reflect any\ntransformations you've requested with this call.\n\npngreadupdateinfo(pngptr, infoptr);\n\nThis is most useful to update the info structure's rowbytes field so you can use it to  allo‐\ncate  your  image  memory.   This  function  will  also  update your palette with the correct\nscreengamma and background if these have been given with the calls above.  You may only call\npngreadupdateinfo() once with a particular infoptr.\n\nAfter you call pngreadupdateinfo(), you can allocate any memory you need to hold  the  im‐\nage.  The row data is simply raw byte data for all forms of images.  As the actual allocation\nvaries  among applications, no example will be given.  If you are allocating one large chunk,\nyou will need to build an array of pointers to each row, as it will be needed for some of the\nfunctions below.\n\nBe sure that your platform can allocate the  buffer  that  you'll  need.   libpng  internally\nchecks   for   oversize   width,   but   you'll   need   to   do  your  own  check  for  num‐\nberofrows*width*pixelsize if you are using a multiple-row buffer:\n\n/* Guard against integer overflow */\nif (numberofrows > PNGSIZEMAX/(width*pixelsize))\npngerror(pngptr, \"imagedata buffer would be too large\");\n\nRemember: Before you call pngreadupdateinfo(), the pngget*() functions return the values\ncorresponding to the original PNG image.  After you call pngreadupdateinfo the values  re‐\nfer  to the image that libpng will output.  Consequently you must call all the pngset func‐\ntions before you call pngreadupdateinfo().  This is particularly important for pngsetin‐\nterlacehandling()  -  if  you  are  going  to  call  pngreadupdateinfo()  you  must  call\npngsetinterlacehandling() before it unless you want to receive interlaced output.\n\n"
                },
                {
                    "name": "Reading image data",
                    "content": "After  you've  allocated memory, you can read the image data.  The simplest way to do this is\nin one function call.  If you are allocating enough memory to hold the whole image,  you  can\njust  call pngreadimage() and libpng will read in all the image data and put it in the mem‐\nory area supplied.  You will need to pass in an array of pointers to each row.\n\nThis function automatically handles interlacing, so you don't  need  to  call  pngsetinter‐\nlacehandling()  (unless  you  call  pngreadupdateinfo())  or  call this function multiple\ntimes, or any of that other stuff necessary with pngreadrows().\n\npngreadimage(pngptr, rowpointers);\n\nwhere rowpointers is:\n\npngbytep rowpointers[height];\n\nYou can point to void or char or whatever you use for pixels.\n\nIf you don't want to read in the whole image at once, you can  use  pngreadrows()  instead.\nIf there is no interlacing (check interlacetype == PNGINTERLACENONE), this is simple:\n\npngreadrows(pngptr, rowpointers, NULL,\nnumberofrows);\n\nwhere rowpointers is the same as in the pngreadimage() call.\n\nIf  you  are doing this just one row at a time, you can do this with a single rowpointer in‐\nstead of an array of rowpointers:\n\npngbytep rowpointer = row;\npngreadrow(pngptr, rowpointer, NULL);\n\nIf the file is interlaced (interlacetype != 0  in  the  IHDR  chunk),  things  get  somewhat\nharder.  The only current (PNG Specification version 1.2) interlacing type for PNG is (inter‐\nlacetype  ==  PNGINTERLACEADAM7);  a  somewhat  complicated  2D interlace scheme, known as\nAdam7, that breaks down an image into seven smaller images of varying size, based on  an  8x8\ngrid.  This number is defined (from libpng 1.5) as PNGINTERLACEADAM7PASSES in png.h\n\nlibpng  can  fill  out  those images or it can give them to you \"as is\".  It is almost always\nbetter to have libpng handle the interlacing for you.  If you want  the  images  filled  out,\nthere  are two ways to do that.  The one mentioned in the PNG specification is to expand each\npixel to cover those pixels that have not been read yet (the \"rectangle\" method).   This  re‐\nsults  in  a  blocky image for the first pass, which gradually smooths out as more pixels are\nread.  The other method is the \"sparkle\" method, where pixels are drawn only in  their  final\nlocations,  with the rest of the image remaining whatever colors they were initialized to be‐\nfore the start of the read.  The first method usually looks better, but tends to  be  slower,\nas there are more pixels to put in the rows.\n\nIf,  as  is  likely,  you  want  libpng  to  expand  the  images,  call  this  before calling\npngstartreadimage() or pngreadupdateinfo():\n\nif (interlacetype == PNGINTERLACEADAM7)\nnumberofpasses\n= pngsetinterlacehandling(pngptr);\n\nThis will return the number of passes needed.  Currently, this is seven, but  may  change  if\nanother  interlace type is added.  This function can be called even if the file is not inter‐\nlaced, where it will return  one  pass.   You  then  need  to  read  the  whole  image  'num‐\nberofpasses' times.  Each time will distribute the pixels from the current pass to the cor‐\nrect  place in the output image, so you need to supply the same rows to pngreadrows in each\npass.\n\nIf you are not going to display the image after each pass, but are going to  wait  until  the\nentire image is read in, use the sparkle effect.  This effect is faster and the end result of\neither  method  is  exactly the same.  If you are planning on displaying the image after each\npass, the \"rectangle\" effect is generally considered the better looking one.\n\nIf you only want the \"sparkle\" effect, just call pngreadrow() or pngreadrows() as normal,\nwith the third parameter NULL.  Make sure you  make  pass  over  the  image  numberofpasses\ntimes, and you don't change the data in the rows between calls.  You can change the locations\nof  the data, just not the data.  Each pass only writes the pixels appropriate for that pass,\nand assumes the data from previous passes is still valid.\n\npngreadrows(pngptr, rowpointers, NULL,\nnumberofrows);\nor\npngreadrow(pngptr, rowpointers, NULL);\n\nIf you only want the first effect (the rectangles), do the same as before except pass the row\nbuffer in the third parameter, and leave the second parameter NULL.\n\npngreadrows(pngptr, NULL, rowpointers,\nnumberofrows);\nor\npngreadrow(pngptr, NULL, rowpointers);\n\nIf you don't want libpng to handle the interlacing details, just call pngreadrows() PNGIN‐\nTERLACEADAM7PASSES times to read in all the images.  Each of the images is a valid image by\nitself; however, you will almost certainly need to distribute the pixels from each  sub-image\nto the correct place.  This is where everything gets very tricky.\n\nIf  you want to retrieve the separate images you must pass the correct number of rows to each\nsuccessive call of pngreadrows().  The calculation gets pretty complicated  for  small  im‐\nages,  where  some sub-images may not even exist because either their width or height ends up\nzero.  libpng provides two macros to help you in 1.5 and later versions:\n\npnguint32 width = PNGPASSCOLS(imagewidth, passnumber);\npnguint32 height = PNGPASSROWS(imageheight, passnumber);\n\nRespectively these tell you the width and height of the sub-image corresponding to  the  num‐\nbered  pass.  'pass' is in in the range 0 to 6 - this can be confusing because the specifica‐\ntion refers to the same passes as 1 to 7!  Be careful, you must  check  both  the  width  and\nheight before calling pngreadrows() and not call it for that pass if either is zero.\n\nYou  can,  of course, read each sub-image row by row.  If you want to produce optimal code to\nmake a pixel-by-pixel transformation of an interlaced image this is the best  approach;  read\neach row of each pass, transform it, and write it out to a new interlaced image.\n\nIf  you  want  to de-interlace the image yourself libpng provides further macros to help that\ntell you where to place the pixels in the output image.  Because the  interlacing  scheme  is\nrectangular  -  sub-image  pixels are always arranged on a rectangular grid - all you need to\nknow for each pass is the starting column and row in the output image of the first pixel plus\nthe spacing between each pixel.  As of libpng 1.5 there are four macros to retrieve this  in‐\nformation:\n\npnguint32 x = PNGPASSSTARTCOL(pass);\npnguint32 y = PNGPASSSTARTROW(pass);\npnguint32 xStep = 1U << PNGPASSCOLSHIFT(pass);\npnguint32 yStep = 1U << PNGPASSROWSHIFT(pass);\n\nThese allow you to write the obvious loop:\n\npnguint32 inputy = 0;\npnguint32 outputy = PNGPASSSTARTROW(pass);\n\nwhile (outputy < outputimageheight)\n{\npnguint32 inputx = 0;\npnguint32 outputx = PNGPASSSTARTCOL(pass);\n\nwhile (outputx < outputimagewidth)\n{\nimage[outputy][outputx] =\nsubimage[pass][inputy][inputx++];\n\noutputx += xStep;\n}\n\n++inputy;\noutputy += yStep;\n}\n\nNotice  that  the  steps  between  successive output rows and columns are returned as shifts.\nThis is possible because the pixels in the subimages are always a power of 2 apart - 1, 2,  4\nor 8 pixels - in the original image.  In practice you may need to directly calculate the out‐\nput  coordinate  given an input coordinate.  libpng provides two further macros for this pur‐\npose:\n\npnguint32 outputx = PNGCOLFROMPASSCOL(inputx, pass);\npnguint32 outputy = PNGROWFROMPASSROW(inputy, pass);\n\nFinally a pair of macros are provided to tell you if a particular image row or column appears\nin a given pass:\n\nint colinpass = PNGCOLININTERLACEPASS(outputx, pass);\nint rowinpass = PNGROWININTERLACEPASS(outputy, pass);\n\nBear in mind that you will probably also need to check the width and height of  the  pass  in\naddition to the above to be sure the pass even exists!\n\nWith any luck you are convinced by now that you don't want to do your own interlace handling.\nIn reality normally the only good reason for doing this is if you are processing PNG files on\na  pixel-by-pixel  basis  and don't want to load the whole file into memory when it is inter‐\nlaced.\n\nlibpng includes a test program, pngvalid, that illustrates reading and writing of  interlaced\nimages.   If  you  can't  get  interlacing to work in your code and don't want to leave it to\nlibpng (the recommended approach), see how pngvalid.c does it.\n\n"
                },
                {
                    "name": "Finishing a sequential read",
                    "content": "After you are finished reading the image through the  low-level  interface,  you  can  finish\nreading the file.\n\nIf  you  want to use a different crc action for handling CRC errors in chunks after the image\ndata, you can call pngsetcrcaction() again at this point.\n\nIf you are interested in comments or time, which may be stored either before or after the im‐\nage data, you should pass the separate pnginfo struct if you want to keep the comments  from\nbefore and after the image separate.\n\npnginfop endinfo = pngcreateinfostruct(pngptr);\n\nif (!endinfo)\n{\npngdestroyreadstruct(&pngptr, &infoptr, NULL);\nreturn ERROR;\n}\n\npngreadend(pngptr, endinfo);\n\nIf you are not interested, you should still call pngreadend() but you can pass NULL, avoid‐\ning  the  need  to create an endinfo structure.  If you do this, libpng will not process any\nchunks after IDAT other than skipping over them and perhaps (depending on  whether  you  have\ncalled pngsetcrcaction) checking their CRCs while looking for the IEND chunk.\n\npngreadend(pngptr, NULL);\n\nIf  you  don't call pngreadend(), then your file pointer will be left pointing to the first\nchunk after the last IDAT, which is probably not what you want if you expect  to  read  some‐\nthing beyond the end of the PNG datastream.\n\nWhen you are done, you can free all memory allocated by libpng like this:\n\npngdestroyreadstruct(&pngptr, &infoptr, &endinfo);\n\nor, if you didn't create an endinfo structure,\n\npngdestroyreadstruct(&pngptr, &infoptr, NULL);\n\nIt  is also possible to individually free the infoptr members that point to libpng-allocated\nstorage with the following function:\n\npngfreedata(pngptr, infoptr, mask, seq)\n\nmask - identifies data to be freed, a mask\ncontaining the bitwise OR of one or\nmore of\nPNGFREEPLTE, PNGFREETRNS,\nPNGFREEHIST, PNGFREEICCP,\nPNGFREEPCAL, PNGFREEROWS,\nPNGFREESCAL, PNGFREESPLT,\nPNGFREETEXT, PNGFREEUNKN,\nor simply PNGFREEALL\n\nseq  - sequence number of item to be freed\n(-1 for all items)\n\nThis function may be safely called when the relevant storage has already been freed,  or  has\nnot  yet  been  allocated, or was allocated by the user and not by libpng,  and will in those\ncases do nothing.  The \"seq\" parameter is ignored if only one item of the selected data type,\nsuch as PLTE, is allowed.  If \"seq\" is not -1, and multiple items are allowed  for  the  data\ntype  identified  in  the  mask, such as text or sPLT, only the n'th item in the structure is\nfreed, where n is \"seq\".\n\nThe default behavior is only to free data that was allocated internally by libpng.  This  can\nbe  changed, so that libpng will not free the data, or so that it will free data that was al‐\nlocated by the user with pngmalloc() or pngcalloc() and passed in via a  pngset*()  func‐\ntion, with\n\npngdatafreer(pngptr, infoptr, freer, mask)\n\nfreer  - one of\nPNGDESTROYWILLFREEDATA\nPNGSETWILLFREEDATA\nPNGUSERWILLFREEDATA\n\nmask   - which data elements are affected\nsame choices as in pngfreedata()\n\nThis  function only affects data that has already been allocated.  You can call this function\nafter reading the PNG data but before calling any pngset*() functions, to  control  whether\nthe  user or the pngset*() function is responsible for freeing any existing data that might\nbe present, and again after the pngset*() functions to control whether the user or  pngde‐\nstroy*()  is supposed to free the data.  When the user assumes responsibility for libpng-al‐\nlocated data, the application must use pngfree() to free it, and when the user transfers re‐\nsponsibility to libpng for data that the user has allocated, the user must have used pngmal‐\nloc() or pngcalloc() to allocate it.\n\nIf you allocated your rowpointers in a single block, as suggested above in  the  description\nof  the high level read interface, you must not transfer responsibility for freeing it to the\npngsetrows or pngreaddestroy function, because they would also try to free the individual\nrowpointers[i].\n\nIf you allocated textptr.text, textptr.lang, and textptr.translatedkeyword separately, do\nnot transfer responsibility for freeing textptr to  libpng,  because  when  libpng  fills  a\npngtext  structure  it  combines these members with the key member, and pngfreedata() will\nfree only textptr.key.  Similarly, if you transfer responsibility for free'ing textptr from\nlibpng to your application, your application must not separately free those members.\n\nThe pngfreedata() function will turn off the \"valid\" flag for anything it  frees.   If  you\nneed  to  turn  the  flag  off  for  a chunk that was freed by your application instead of by\nlibpng, you can use\n\npngsetinvalid(pngptr, infoptr, mask);\n\nmask - identifies the chunks to be made invalid,\ncontaining the bitwise OR of one or\nmore of\nPNGINFOgAMA, PNGINFOsBIT,\nPNGINFOcHRM, PNGINFOPLTE,\nPNGINFOtRNS, PNGINFObKGD,\nPNGINFOeXIf,\nPNGINFOhIST, PNGINFOpHYs,\nPNGINFOoFFs, PNGINFOtIME,\nPNGINFOpCAL, PNGINFOsRGB,\nPNGINFOiCCP, PNGINFOsPLT,\nPNGINFOsCAL, PNGINFOIDAT\n\nFor a more compact example of reading a PNG image, see the file example.c.\n\n"
                },
                {
                    "name": "Reading PNG files progressively",
                    "content": "The progressive reader is slightly different from the  non-progressive  reader.   Instead  of\ncalling   pngreadinfo(),   pngreadrows(),  and  pngreadend(),  you  make  one  call  to\npngprocessdata(), which calls callbacks when it has the info, a row, or the end of the  im‐\nage.  You set up these callbacks with pngsetprogressivereadfn().  You don't have to worry\nabout  the  input/output functions of libpng, as you are giving the library the data directly\nin pngprocessdata().  I will assume that you have read the section  on  reading  PNG  files\nabove, so I will only highlight the differences (although I will show all of the code).\n\npngstructp pngptr; pnginfop infoptr;\n\n/*  An example code fragment of how you would\ninitialize the progressive reader in your\napplication. */\nint\ninitializepngreader()\n{\npngptr = pngcreatereadstruct\n(PNGLIBPNGVERSTRING, (pngvoidp)usererrorptr,\nusererrorfn, userwarningfn);\n\nif (!pngptr)\nreturn ERROR;\n\ninfoptr = pngcreateinfostruct(pngptr);\n\nif (!infoptr)\n{\npngdestroyreadstruct(&pngptr, NULL, NULL);\nreturn ERROR;\n}\n\nif (setjmp(pngjmpbuf(pngptr)))\n{\npngdestroyreadstruct(&pngptr, &infoptr, NULL);\nreturn ERROR;\n}\n\n/* This one's new.  You can provide functions\nto be called when the header info is valid,\nwhen each row is completed, and when the image\nis finished.  If you aren't using all functions,\nyou can specify NULL parameters.  Even when all\nthree functions are NULL, you need to call\npngsetprogressivereadfn().  You can use\nany struct as the userptr (cast to a void pointer\nfor the function call), and retrieve the pointer\nfrom inside the callbacks using the function\n\npnggetprogressiveptr(pngptr);\n\nwhich will return a void pointer, which you have\nto cast appropriately.\n*/\npngsetprogressivereadfn(pngptr, (void *)userptr,\ninfocallback, rowcallback, endcallback);\n\nreturn 0;\n}\n\n/* A code fragment that you call as you receive blocks\nof data */\nint\nprocessdata(pngbytep buffer, pnguint32 length)\n{\nif (setjmp(pngjmpbuf(pngptr)))\n{\npngdestroyreadstruct(&pngptr, &infoptr, NULL);\nreturn ERROR;\n}\n\n/* This one's new also.  Simply give it a chunk\nof data from the file stream (in order, of\ncourse).  On machines with segmented memory\nmodels machines, don't give it any more than\n64K.  The library seems to run fine with sizes\nof 4K. Although you can give it much less if\nnecessary (I assume you can give it chunks of\n1 byte, I haven't tried less than 256 bytes\nyet).  When this function returns, you may\nwant to display any rows that were generated\nin the row callback if you don't already do\nso there.\n*/\npngprocessdata(pngptr, infoptr, buffer, length);\n\n/* At this point you can call pngprocessdataskip if\nyou want to handle data the library will skip yourself;\nit simply returns the number of bytes to skip (and stops\nlibpng skipping that number of bytes on the next\npngprocessdata call).\nreturn 0;\n}\n\n/* This function is called (as set by\npngsetprogressivereadfn() above) when enough data\nhas been supplied so all of the header has been\nread.\n*/\nvoid\ninfocallback(pngstructp pngptr, pnginfop info)\n{\n/* Do any setup here, including setting any of\nthe transformations mentioned in the Reading\nPNG files section.  For now, you must call\neither pngstartreadimage() or\npngreadupdateinfo() after all the\ntransformations are set (even if you don't set\nany).  You may start getting rows before\npngprocessdata() returns, so this is your\nlast chance to prepare for that.\n\nThis is where you turn on interlace handling,\nassuming you don't want to do it yourself.\n\nIf you need to you can stop the processing of\nyour original input data at this point by calling\npngprocessdatapause.  This returns the number\nof unprocessed bytes from the last pngprocessdata\ncall - it is up to you to ensure that the next call\nsees these bytes again.  If you don't want to bother\nwith this you can get libpng to cache the unread\nbytes by setting the 'save' parameter (see png.h) but\nthen libpng will have to copy the data internally.\n*/\n}\n\n/* This function is called when each row of image\ndata is complete */\nvoid\nrowcallback(pngstructp pngptr, pngbytep newrow,\npnguint32 rownum, int pass)\n{\n/* If the image is interlaced, and you turned\non the interlace handler, this function will\nbe called for every row in every pass.  Some\nof these rows will not be changed from the\nprevious pass.  When the row is not changed,\nthe newrow variable will be NULL.  The rows\nand passes are called in order, so you don't\nreally need the rownum and pass, but I'm\nsupplying them because it may make your life\neasier.\n\nIf you did not turn on interlace handling then\nthe callback is called for each row of each\nsub-image when the image is interlaced.  In this\ncase 'rownum' is the row in the sub-image, not\nthe row in the output image as it is in all other\ncases.\n\nFor the non-NULL rows of interlaced images when\nyou have switched on libpng interlace handling,\nyou must call pngprogressivecombinerow()\npassing in the row and the old row.  You can\ncall this function for NULL rows (it will just\nreturn) and for non-interlaced images (it just\ndoes the memcpy for you) if it will make the\ncode easier.  Thus, you can just do this for\nall cases if you switch on interlace handling;\n*/\n\npngprogressivecombinerow(pngptr, oldrow,\nnewrow);\n\n/* where oldrow is what was displayed\npreviously for the row.  Note that the first\npass (pass == 0, really) will completely cover\nthe old row, so the rows do not have to be\ninitialized.  After the first pass (and only\nfor interlaced images), you will have to pass\nthe current row, and the function will combine\nthe old row and the new row.\n\nYou can also call pngprocessdatapause in this\ncallback - see above.\n*/\n}\n\nvoid\nendcallback(pngstructp pngptr, pnginfop info)\n{\n/* This function is called after the whole image\nhas been read, including any chunks after the\nimage (up to and including the IEND).  You\nwill usually have the same info chunk as you\nhad in the header, although some data may have\nbeen added to the comments and time fields.\n\nMost people won't do much here, perhaps setting\na flag that marks the image as finished.\n*/\n}\n\n\n\n\nIV. Writing\nMuch of this is very similar to reading.  However, everything of importance is repeated here,\nso you won't have to constantly look back up in the reading section to understand writing.\n\n"
                },
                {
                    "name": "Setup",
                    "content": "You will want to do the I/O initialization before you get into libpng, so if it doesn't work,\nyou  don't  have  anything to undo. If you are not using the standard I/O functions, you will\nneed to replace them with custom writing functions.  See  the  discussion  under  Customizing\nlibpng.\n\nFILE *fp = fopen(filename, \"wb\");\n\nif (!fp)\nreturn ERROR;\n\nNext,  pngstruct  and  pnginfo  need to be allocated and initialized.  As these can be both\nrelatively large, you may not want to store these on the stack, unless you have  stack  space\nto  spare.   Of course, you will want to check if they return NULL.  If you are also reading,\nyou won't want to name your read structure and your write structure both \"pngptr\";  you  can\ncall  them anything you like, such as \"readptr\" and \"writeptr\".  Look at pngtest.c, for ex‐\nample.\n\npngstructp pngptr = pngcreatewritestruct\n(PNGLIBPNGVERSTRING, (pngvoidp)usererrorptr,\nusererrorfn, userwarningfn);\n\nif (!pngptr)\nreturn ERROR;\n\npnginfop infoptr = pngcreateinfostruct(pngptr);\nif (!infoptr)\n{\npngdestroywritestruct(&pngptr, NULL);\nreturn ERROR;\n}\n\nIf you want to use your own memory allocation routines, define PNGUSERMEMSUPPORTED and use\npngcreatewritestruct2() instead of pngcreatewritestruct():\n\npngstructp pngptr = pngcreatewritestruct2\n(PNGLIBPNGVERSTRING, (pngvoidp)usererrorptr,\nusererrorfn, userwarningfn, (pngvoidp)\nusermemptr, usermallocfn, userfreefn);\n\nAfter you have these structures, you will need to set up the error handling.  When libpng en‐\ncounters an error, it expects to longjmp() back to your routine.  Therefore, you will need to\ncall setjmp() and pass the pngjmpbuf(pngptr).  If you write the file  from  different  rou‐\ntines,  you  will  need  to update the pngjmpbuf(pngptr) every time you enter a new routine\nthat will call a png*() function.  See your documentation of setjmp/longjmp  for  your  com‐\npiler for more information on setjmp/longjmp.  See the discussion on libpng error handling in\nthe Customizing Libpng section below for more information on the libpng error handling.\n\nif (setjmp(pngjmpbuf(pngptr)))\n{\npngdestroywritestruct(&pngptr, &infoptr);\nfclose(fp);\nreturn ERROR;\n}\n...\nreturn;\n\nIf  you  would  rather  avoid the complexity of setjmp/longjmp issues, you can compile libpng\nwith PNGNOSETJMP, in which case errors will result in a call to PNGABORT() which  defaults\nto abort().\n\nYou  can  #define  PNGABORT() to a function that does something more useful than abort(), as\nlong as your function does not return.\n\nChecking for invalid palette index on write was added at libpng 1.5.10.  If a pixel  contains\nan invalid (out-of-range) index libpng issues a benign error.  This is enabled by default be‐\ncause  this  condition is an error according to the PNG specification, Clause 11.3.2, but the\nerror can be ignored in each pngptr with\n\npngsetcheckforinvalidindex(pngptr, 0);\n\nIf the error is ignored, or if pngbenignerror() treats it as a warning, any invalid  pixels\nare  written as-is by the encoder, resulting in an invalid PNG datastream as output.  In this\ncase the application is responsible for ensuring that the pixel indexes are in range when  it\nwrites a PLTE chunk with fewer entries than the bit depth would allow.\n\nNow  you  need  to  set  up the output code.  The default for libpng is to use the C function\nfwrite().  If you use  this,  you  will  need  to  pass  a  valid  FILE  *  in  the  function\npnginitio().  Be sure that the file is opened in binary mode.  Again, if you wish to handle\nwriting  data  in  another  way, see the discussion on libpng I/O handling in the Customizing\nLibpng section below.\n\npnginitio(pngptr, fp);\n\nIf you are embedding your PNG into a datastream such as MNG, and don't want libpng  to  write\nthe 8-byte signature, or if you have already written the signature in your application, use\n\npngsetsigbytes(pngptr, 8);\n\nto inform libpng that it should not write a signature.\n\n"
                },
                {
                    "name": "Write callbacks",
                    "content": "At this point, you can set up a callback function that will be called after each row has been\nwritten,  which  you  can  use to control a progress meter or the like.  It's demonstrated in\npngtest.c.  You must supply a function\n\nvoid writerowcallback(pngstructp pngptr, pnguint32 row,\nint pass)\n{\n/* put your code here */\n}\n\n(You can give it another name that you like instead of \"writerowcallback\")\n\nTo inform libpng about your function, use\n\npngsetwritestatusfn(pngptr, writerowcallback);\n\nWhen this function is called the row has already been completely processed and  it  has  also\nbeen written out.  The 'row' and 'pass' refer to the next row to be handled.  For the non-in‐\nterlaced case the row that was just handled is simply one less than the passed in row number,\nand  pass will always be 0.  For the interlaced case the same applies unless the row value is\n0, in which case the row just handled was the last one from one of the preceding passes.  Be‐\ncause interlacing may skip a pass you  cannot  be  sure  that  the  preceding  pass  is  just\n'pass-1',  if  you really need to know what the last pass is record (row,pass) from the call‐\nback and use the last recorded value each time.\n\nAs with the user transform you can find the output row using the PNGROWFROMPASSROW macro.\n\nYou now have the option of modifying how the compression library  will  run.   The  following\nfunctions  are mainly for testing, but may be useful in some cases, like if you need to write\nPNG files extremely fast and are willing to give up some compression, or if you want  to  get\nthe  maximum  possible  compression at the expense of slower writing.  If you have no special\nneeds in this area, let the library do what it wants by not calling this function at all,  as\nit  has  been  tuned  to  deliver  a  good  speed/compression  ratio. The second parameter to\npngsetfilter() is the filter method, for which the only valid values are 0 (as of the  July\n1999 PNG specification, version 1.2) or 64 (if you are writing a PNG datastream that is to be\nembedded  in  a  MNG  datastream).  The third parameter is a flag that indicates which filter\ntype(s) are to be tested for each scanline.  See the PNG specification  for  details  on  the\nspecific filter types.\n\n\n/* turn on or off filtering, and/or choose\nspecific filters.  You can use either a single\nPNGFILTERVALUENAME or the bitwise OR of one\nor more PNGFILTERNAME masks.\n*/\npngsetfilter(pngptr, 0,\nPNGFILTERNONE  | PNGFILTERVALUENONE |\nPNGFILTERSUB   | PNGFILTERVALUESUB  |\nPNGFILTERUP    | PNGFILTERVALUEUP   |\nPNGFILTERAVG   | PNGFILTERVALUEAVG  |\nPNGFILTERPAETH | PNGFILTERVALUEPAETH|\nPNGALLFILTERS  | PNGFASTFILTERS);\n\nIf  an  application  wants  to start and stop using particular filters during compression, it\nshould start out with all of the filters (to ensure that the previous row of pixels  will  be\nstored  in  case it's needed later), and then add and remove them after the start of compres‐\nsion.\n\nIf you are writing a PNG datastream that is to be embedded in a MNG  datastream,  the  second\nparameter can be either 0 or 64.\n\nThe  pngsetcompression*()  functions interface to the zlib compression library, and should\nmostly be ignored unless you really know what you are doing.  The only generally useful  call\nis  pngsetcompressionlevel() which changes how much time zlib spends on trying to compress\nthe image data.  See the Compression Library  (zlib.h  and  algorithm.txt,  distributed  with\nzlib) for details on the compression levels.\n\n#include zlib.h\n\n/* Set the zlib compression level */\npngsetcompressionlevel(pngptr,\nZBESTCOMPRESSION);\n\n/* Set other zlib parameters for compressing IDAT */\npngsetcompressionmemlevel(pngptr, 8);\npngsetcompressionstrategy(pngptr,\nZDEFAULTSTRATEGY);\npngsetcompressionwindowbits(pngptr, 15);\npngsetcompressionmethod(pngptr, 8);\npngsetcompressionbuffersize(pngptr, 8192)\n\n/* Set zlib parameters for text compression\n* If you don't call these, the parameters\n* fall back on those defined for IDAT chunks\n*/\npngsettextcompressionmemlevel(pngptr, 8);\npngsettextcompressionstrategy(pngptr,\nZDEFAULTSTRATEGY);\npngsettextcompressionwindowbits(pngptr, 15);\npngsettextcompressionmethod(pngptr, 8);\n\n"
                },
                {
                    "name": "Setting the contents of info for output",
                    "content": "You now need to fill in the pnginfo structure with all the data you wish to write before the\nactual  image.  Note that the only thing you are allowed to write after the image is the text\nchunks and the time chunk (as of PNG Specification 1.2, anyway).  See pngwriteend() and the\nlatest PNG specification for more information on that.  If you wish to write them before  the\nimage,  fill them in now, and flag that data as being valid.  If you want to wait until after\nthe data, don't fill them until pngwriteend().  For all the fields in  pnginfo  and  their\ndata  types,  see png.h.  For explanations of what the fields contain, see the PNG specifica‐\ntion.\n\nSome of the more important parts of the pnginfo are:\n\npngsetIHDR(pngptr, infoptr, width, height,\nbitdepth, colortype, interlacetype,\ncompressiontype, filtermethod)\n\nwidth          - holds the width of the image\nin pixels (up to 2^31).\n\nheight         - holds the height of the image\nin pixels (up to 2^31).\n\nbitdepth      - holds the bit depth of one of the\nimage channels.\n(valid values are 1, 2, 4, 8, 16\nand depend also on the\ncolortype.  See also significant\nbits (sBIT) below).\n\ncolortype     - describes which color/alpha\nchannels are present.\nPNGCOLORTYPEGRAY\n(bit depths 1, 2, 4, 8, 16)\nPNGCOLORTYPEGRAYALPHA\n(bit depths 8, 16)\nPNGCOLORTYPEPALETTE\n(bit depths 1, 2, 4, 8)\nPNGCOLORTYPERGB\n(bitdepths 8, 16)\nPNGCOLORTYPERGBALPHA\n(bitdepths 8, 16)\n\nPNGCOLORMASKPALETTE\nPNGCOLORMASKCOLOR\nPNGCOLORMASKALPHA\n\ninterlacetype - PNGINTERLACENONE or\nPNGINTERLACEADAM7\n\ncompressiontype - (must be\nPNGCOMPRESSIONTYPEDEFAULT)\n\nfiltermethod  - (must be PNGFILTERTYPEDEFAULT\nor, if you are writing a PNG to\nbe embedded in a MNG datastream,\ncan also be\nPNGINTRAPIXELDIFFERENCING)\n\nIf you call pngsetIHDR(), the call must appear before any of the  other  pngset*()  func‐\ntions,  because  they  might  require  access  to  some  of the IHDR settings.  The remaining\npngset*() functions can be called in any order.\n\nIf you wish, you can reset the compressiontype, interlacetype, or  filtermethod  later  by\ncalling  pngsetIHDR()  again;  if you do this, the width, height, bitdepth, and colortype\nmust be the same in each call.\n\npngsetPLTE(pngptr, infoptr, palette,\nnumpalette);\n\npalette        - the palette for the file\n(array of pngcolor)\nnumpalette    - number of entries in the palette\n\n\npngsetgAMA(pngptr, infoptr, filegamma);\npngsetgAMAfixed(pngptr, infoptr, intfilegamma);\n\nfilegamma     - the gamma at which the image was\ncreated (PNGINFOgAMA)\n\nintfilegamma - 100,000 times the gamma at which\nthe image was created\n\npngsetcHRM(pngptr, infoptr,  whitex, whitey, redx, redy,\ngreenx, greeny, bluex, bluey)\npngsetcHRMXYZ(pngptr, infoptr, redX, redY, redZ, greenX,\ngreenY, greenZ, blueX, blueY, blueZ)\npngsetcHRMfixed(pngptr, infoptr, intwhitex, intwhitey,\nintredx, intredy, intgreenx, intgreeny,\nintbluex, intbluey)\npngsetcHRMXYZfixed(pngptr, infoptr, intredX, intredY,\nintredZ, intgreenX, intgreenY, intgreenZ,\nintblueX, intblueY, intblueZ)\n\n{white,red,green,blue}{x,y}\nA color space encoding specified using the chromaticities\nof the end points and the white point.\n\n{red,green,blue}{X,Y,Z}\nA color space encoding specified using the encoding end\npoints - the CIE tristimulus specification of the intended\ncolor of the red, green and blue channels in the PNG RGB\ndata.  The white point is simply the sum of the three end\npoints.\n\npngsetsRGB(pngptr, infoptr, srgbintent);\n\nsrgbintent    - the rendering intent\n(PNGINFOsRGB) The presence of\nthe sRGB chunk means that the pixel\ndata is in the sRGB color space.\nThis chunk also implies specific\nvalues of gAMA and cHRM.  Rendering\nintent is the CSS-1 property that\nhas been defined by the International\nColor Consortium\n(http://www.color.org).\nIt can be one of\nPNGsRGBINTENTSATURATION,\nPNGsRGBINTENTPERCEPTUAL,\nPNGsRGBINTENTABSOLUTE, or\nPNGsRGBINTENTRELATIVE.\n\n\npngsetsRGBgAMAandcHRM(pngptr, infoptr,\nsrgbintent);\n\nsrgbintent    - the rendering intent\n(PNGINFOsRGB) The presence of the\nsRGB chunk means that the pixel\ndata is in the sRGB color space.\nThis function also causes gAMA and\ncHRM chunks with the specific values\nthat are consistent with sRGB to be\nwritten.\n\npngsetiCCP(pngptr, infoptr, name, compressiontype,\nprofile, proflen);\n\nname             - The profile name.\n\ncompressiontype - The compression type; always\nPNGCOMPRESSIONTYPEBASE for PNG 1.0.\nYou may give NULL to this argument to\nignore it.\n\nprofile          - International Color Consortium color\nprofile data. May contain NULs.\n\nproflen          - length of profile data in bytes.\n\npngsetsBIT(pngptr, infoptr, sigbit);\n\nsigbit        - the number of significant bits for\n(PNGINFOsBIT) each of the gray, red,\ngreen, and blue channels, whichever are\nappropriate for the given color type\n(pngcolor16)\n\npngsettRNS(pngptr, infoptr, transalpha,\nnumtrans, transcolor);\n\ntransalpha    - array of alpha (transparency)\nentries for palette (PNGINFOtRNS)\n\nnumtrans      - number of transparent entries\n(PNGINFOtRNS)\n\ntranscolor    - graylevel or color sample values\n(in order red, green, blue) of the\nsingle transparent color for\nnon-paletted images (PNGINFOtRNS)\n\npngseteXIf1(pngptr, infoptr, numexif, exif);\n\nexif           - Exif profile (array of pngbyte)\n(PNGINFOeXIf)\n\npngsethIST(pngptr, infoptr, hist);\n\nhist           - histogram of palette (array of\npnguint16) (PNGINFOhIST)\n\npngsettIME(pngptr, infoptr, modtime);\n\nmodtime       - time image was last modified\n(PNGINFOtIME)\n\npngsetbKGD(pngptr, infoptr, background);\n\nbackground     - background color (of type\npngcolor16p) (PNGINFObKGD)\n\npngsettext(pngptr, infoptr, textptr, numtext);\n\ntextptr       - array of pngtext holding image\ncomments\n\ntextptr[i].compression - type of compression used\non \"text\" PNGTEXTCOMPRESSIONNONE\nPNGTEXTCOMPRESSIONzTXt\nPNGITXTCOMPRESSIONNONE\nPNGITXTCOMPRESSIONzTXt\ntextptr[i].key   - keyword for comment.  Must contain\n1-79 characters.\ntextptr[i].text  - text comments for current\nkeyword.  Can be NULL or empty.\ntextptr[i].textlength - length of text string,\nafter decompression, 0 for iTXt\ntextptr[i].itxtlength - length of itxt string,\nafter decompression, 0 for tEXt/zTXt\ntextptr[i].lang  - language of comment (NULL or\nempty for unknown).\ntextptr[i].translatedkeyword  - keyword in UTF-8 (NULL\nor empty for unknown).\n\nNote that the itxtlength, lang, and langkey\nmembers of the textptr structure only exist when the\nlibrary is built with iTXt chunk support.  Prior to\nlibpng-1.4.0 the library was built by default without\niTXt support. Also note that when iTXt is supported,\nthey contain NULL pointers when the \"compression\"\nfield contains PNGTEXTCOMPRESSIONNONE or\nPNGTEXTCOMPRESSIONzTXt.\n\nnumtext       - number of comments\n\npngsetsPLT(pngptr, infoptr, &paletteptr,\nnumspalettes);\n\npaletteptr    - array of pngsPLTstruct structures\nto be added to the list of palettes\nin the info structure.\nnumspalettes  - number of palette structures to be\nadded.\n\npngsetoFFs(pngptr, infoptr, offsetx, offsety,\nunittype);\n\noffsetx  - positive offset from the left\nedge of the screen\n\noffsety  - positive offset from the top\nedge of the screen\n\nunittype - PNGOFFSETPIXEL, PNGOFFSETMICROMETER\n\npngsetpHYs(pngptr, infoptr, resx, resy,\nunittype);\n\nresx       - pixels/unit physical resolution\nin x direction\n\nresy       - pixels/unit physical resolution\nin y direction\n\nunittype   - PNGRESOLUTIONUNKNOWN,\nPNGRESOLUTIONMETER\n\npngsetsCAL(pngptr, infoptr, unit, width, height)\n\nunit        - physical scale units (an integer)\n\nwidth       - width of a pixel in physical scale units\n\nheight      - height of a pixel in physical scale units\n(width and height are doubles)\n\npngsetsCALs(pngptr, infoptr, unit, width, height)\n\nunit        - physical scale units (an integer)\n\nwidth       - width of a pixel in physical scale units\nexpressed as a string\n\nheight      - height of a pixel in physical scale units\n(width and height are strings like \"2.54\")\n\npngsetunknownchunks(pngptr, infoptr, &unknowns,\nnumunknowns)\n\nunknowns          - array of pngunknownchunk\nstructures holding unknown chunks\nunknowns[i].name  - name of unknown chunk\nunknowns[i].data  - data of unknown chunk\nunknowns[i].size  - size of unknown chunk's data\nunknowns[i].location - position to write chunk in file\n0: do not write chunk\nPNGHAVEIHDR: before PLTE\nPNGHAVEPLTE: before IDAT\nPNGAFTERIDAT: after IDAT\n\nThe \"location\" member is set automatically according to what part of the output file has  al‐\nready  been  written.   You  can  change  its value after calling pngsetunknownchunks() as\ndemonstrated in pngtest.c.  Within each of the \"locations\", the chunks are sequenced  accord‐\ning  to  their  position  in  the structure (that is, the value of \"i\", which is the order in\nwhich the chunk was either read from the input file or defined with pngsetunknownchunks).\n\nA quick word about text and numtext.  text is an array of pngtext structures.  numtext  is\nthe  number of valid structures in the array.  Each pngtext structure holds a language code,\na keyword, a text value, and a compression type.\n\nThe compression types have the same valid numbers as the compression types of the image data.\nCurrently, the only valid number is zero.  However, you can store text either  compressed  or\nuncompressed,  unlike  images,  which always have to be compressed.  So if you don't want the\ntext compressed, set the compression type to  PNGTEXTCOMPRESSIONNONE.   Because  tEXt  and\nzTXt  chunks  don't  have  a  language  field,  if  you  specify PNGTEXTCOMPRESSIONNONE or\nPNGTEXTCOMPRESSIONzTXt any language code or translated keyword will not be written out.\n\nUntil text gets around a few hundred bytes, it is not worth compressing it.  After  the  text\nhas been written out to the file, the compression type is set to PNGTEXTCOMPRESSIONNONEWR\nor  PNGTEXTCOMPRESSIONzTXtWR,  so that it isn't written out again at the end (in case you\nare calling pngwriteend() with the same struct).\n\nThe keywords that are given in the PNG Specification are:\n\nTitle            Short (one line) title or\ncaption for image\n\nAuthor           Name of image's creator\n\nDescription      Description of image (possibly long)\n\nCopyright        Copyright notice\n\nCreation Time    Time of original image creation\n(usually RFC 1123 format, see below)\n\nSoftware         Software used to create the image\n\nDisclaimer       Legal disclaimer\n\nWarning          Warning of nature of content\n\nSource           Device used to create the image\n\nComment          Miscellaneous comment; conversion\nfrom other image format\n\nThe keyword-text pairs work like this.  Keywords should be short simple descriptions of  what\nthe  comment  is about.  Some typical keywords are found in the PNG specification, as is some\nrecommendations on keywords.  You can repeat keywords in a file.  You  can  even  write  some\ntext  before the image and some after.  For example, you may want to put a description of the\nimage before the image, but leave the disclaimer until after, so viewers working  over  modem\nconnections don't have to wait for the disclaimer to go over the modem before they start see‐\ning the image.  Finally, keywords should be full words, not abbreviations.  Keywords and text\nare  in the ISO 8859-1 (Latin-1) character set (a superset of regular ASCII) and can not con‐\ntain NUL characters, and should not contain control or other unprintable characters.  To make\nthe comments widely readable, stick with basic ASCII, and avoid  machine  specific  character\nset extensions like the IBM-PC character set.  The keyword must be present, but you can leave\noff  the  text  string on non-compressed pairs.  Compressed pairs must have a text string, as\nonly the text string is compressed anyway, so the compression would be meaningless.\n\nPNG supports modification time via the pngtime structure.  Two conversion routines are  pro‐\nvided,  pngconvertfromtimet()  for timet and pngconvertfromstructtm() for struct tm.\nThe timet routine uses gmtime().  You don't have to use either of these, but if you wish  to\nfill  in the pngtime structure directly, you should provide the time in universal time (GMT)\nif possible instead of your local time.  Note that the year number is  the  full  year  (e.g.\n1998, rather than 98 - PNG is year 2000 compliant!), and that months start with 1.\n\nIf  you  want  to  store the time of the original image creation, you should use a plain tEXt\nchunk with the \"Creation Time\" keyword.  This is necessary because the \"creation time\"  of  a\nPNG  image  is somewhat vague, depending on whether you mean the PNG file, the time the image\nwas created in a non-PNG format, a still photo from which the image was scanned, or  possibly\nthe  subject matter itself.  In order to facilitate machine-readable dates, it is recommended\nthat the \"Creation Time\" tEXt chunk use RFC 1123 format dates (e.g.  \"22  May  1997  18:07:10\nGMT\"),  although  this  isn't a requirement.  Unlike the tIME chunk, the \"Creation Time\" tEXt\nchunk is not expected to be automatically changed by the software.  To facilitate the use  of\nRFC  1123  dates,  a function pngconverttorfc1123buffer(buffer, pngtimep) is provided to\nconvert from PNG time to an RFC 1123 format string.  The  caller  must  provide  a  writeable\nbuffer of at least 29 bytes.\n\n"
                },
                {
                    "name": "Writing unknown chunks",
                    "content": "You  can use the pngsetunknownchunks function to queue up private chunks for writing.  You\ngive it a chunk name, location, raw data, and a size.  You  also  must  use  pngsetkeepun‐\nknownchunks()  to  ensure  that  libpng  will  handle them.  That's all there is to it.  The\nchunks will be written by the next following pngwriteinfobeforePLTE,  pngwriteinfo,  or\npngwriteend  function,  depending  upon the specified location.  Any chunks previously read\ninto the info structure's unknown-chunk list will also be written out in a sequence that sat‐\nisfies the PNG specification's ordering rules.\n\nHere is an example of writing two private chunks, prVt and miNE:\n\n#ifdef PNGWRITEUNKNOWNCHUNKSSUPPORTED\n/* Set unknown chunk data */\npngunknownchunk unkchunk[2];\nstrcpy((char *) unkchunk[0].name, \"prVt\";\nunkchunk[0].data = (unsigned char *) \"PRIVATE DATA\";\nunkchunk[0].size = strlen(unkchunk[0].data)+1;\nunkchunk[0].location = PNGHAVEIHDR;\nstrcpy((char *) unkchunk[1].name, \"miNE\";\nunkchunk[1].data = (unsigned char *) \"MY CHUNK DATA\";\nunkchunk[1].size = strlen(unkchunk[0].data)+1;\nunkchunk[1].location = PNGAFTERIDAT;\npngsetunknownchunks(writeptr, writeinfoptr,\nunkchunk, 2);\n/* Needed because miNE is not safe-to-copy */\npngsetkeepunknownchunks(png, PNGHANDLECHUNKALWAYS,\n(pngbytep) \"miNE\", 1);\n# if PNGLIBPNGVER < 10600\n/* Deal with unknown chunk location bug in 1.5.x and earlier */\npngsetunknownchunklocation(png, info, 0, PNGHAVEIHDR);\npngsetunknownchunklocation(png, info, 1, PNGAFTERIDAT);\n# endif\n# if PNGLIBPNGVER < 10500\n/* PNGAFTERIDAT writes two copies of the chunk prior to libpng-1.5.0,\n* one before IDAT and another after IDAT, so don't use it; only use\n* PNGHAVEIHDR location.  This call resets the location previously\n* set by assignment and pngsetunknownchunklocation() for chunk 1.\n*/\npngsetunknownchunklocation(png, info, 1, PNGHAVEIHDR);\n# endif\n#endif\n\n"
                },
                {
                    "name": "The high-level write interface",
                    "content": "At this point there are two ways to proceed;  through  the  high-level  write  interface,  or\nthrough  a  sequence  of low-level write operations.  You can use the high-level interface if\nyour image data is present in the info structure.  All  defined  output  transformations  are\npermitted, enabled by the following masks.\n\nPNGTRANSFORMIDENTITY      No transformation\nPNGTRANSFORMPACKING       Pack 1, 2 and 4-bit samples\nPNGTRANSFORMPACKSWAP      Change order of packed\npixels to LSB first\nPNGTRANSFORMINVERTMONO   Invert monochrome images\nPNGTRANSFORMSHIFT         Normalize pixels to the\nsBIT depth\nPNGTRANSFORMBGR           Flip RGB to BGR, RGBA\nto BGRA\nPNGTRANSFORMSWAPALPHA    Flip RGBA to ARGB or GA\nto AG\nPNGTRANSFORMINVERTALPHA  Change alpha from opacity\nto transparency\nPNGTRANSFORMSWAPENDIAN   Byte-swap 16-bit samples\nPNGTRANSFORMSTRIPFILLER        Strip out filler\nbytes (deprecated).\nPNGTRANSFORMSTRIPFILLERBEFORE Strip out leading\nfiller bytes\nPNGTRANSFORMSTRIPFILLERAFTER  Strip out trailing\nfiller bytes\n\nIf  you  have valid image data in the info structure (you can use pngsetrows() to put image\ndata in the info structure), simply do this:\n\npngwritepng(pngptr, infoptr, pngtransforms, NULL)\n\nwhere pngtransforms is an integer containing the bitwise OR of some  set  of  transformation\nflags.   This call is equivalent to pngwriteinfo(), followed the set of transformations in‐\ndicated by the transform mask, then pngwriteimage(), and finally pngwriteend().\n\n(The final parameter of this call is not yet used.  Someday it might point to  transformation\nparameters required by some future output transform.)\n\nYou  must  use  pngtransforms  and  not  call any pngsettransform() functions when you use\npngwritepng().\n\n"
                },
                {
                    "name": "The low-level write interface",
                    "content": "If you are going the low-level route instead, you are now ready to write all the file  infor‐\nmation up to the actual image data.  You do this with a call to pngwriteinfo().\n\npngwriteinfo(pngptr, infoptr);\n\nNote  that  there  is  one transformation you may need to do before pngwriteinfo().  In PNG\nfiles, the alpha channel in an image is the level of opacity.  If your data is supplied as  a\nlevel  of  transparency,  you  can invert the alpha channel before you write it, so that 0 is\nfully transparent and 255 (in 8-bit or paletted images) or 65535 (in 16-bit images) is  fully\nopaque, with\n\npngsetinvertalpha(pngptr);\n\nThis  must appear before pngwriteinfo() instead of later with the other transformations be‐\ncause in the case of paletted images the tRNS chunk data has to be inverted before  the  tRNS\nchunk  is written.  If your image is not a paletted image, the tRNS data (which in such cases\nrepresents a single color to be rendered as transparent) won't need to be  changed,  and  you\ncan safely do this transformation after your pngwriteinfo() call.\n\nIf  you need to write a private chunk that you want to appear before the PLTE chunk when PLTE\nis present, you can write the PNG info in two steps, and insert code to write your own  chunk\nbetween them:\n\npngwriteinfobeforePLTE(pngptr, infoptr);\npngsetunknownchunks(pngptr, infoptr, ...);\npngwriteinfo(pngptr, infoptr);\n\nAfter  you've  written the file information, you can set up the library to handle any special\ntransformations of the image data.  The various ways to transform the data will be  described\nin  the  order  that they should occur.  This is important, as some of these change the color\ntype and/or bit depth of the data, and some others only work on certain color types  and  bit\ndepths.   Even  though  each transformation checks to see if it has data that it can do some‐\nthing with, you should make sure to only enable a transformation if it will be valid for  the\ndata.  For example, don't swap red and blue on grayscale data.\n\nPNG  files  store  RGB pixels packed into 3 or 6 bytes.  This code tells the library to strip\ninput data that has 4 or 8 bytes per pixel down to 3  or  6  bytes  (or  strip  2  or  4-byte\ngrayscale+filler data to 1 or 2 bytes per pixel).\n\npngsetfiller(pngptr, 0, PNGFILLERBEFORE);\n\nwhere  the 0 is unused, and the location is either PNGFILLERBEFORE or PNGFILLERAFTER, de‐\npending upon whether the filler byte in the pixel is stored XRGB or RGBX.\n\nPNG files pack pixels of bit depths 1, 2, and 4 into bytes as small as  they  can,  resulting\nin,  for  example, 8 pixels per byte for 1 bit files.  If the data is supplied at 1 pixel per\nbyte, use this code, which will correctly pack the pixels into a single byte:\n\npngsetpacking(pngptr);\n\nPNG files reduce possible bit depths to 1, 2, 4, 8, and 16.  If your data is of  another  bit\ndepth,  you  can  write an sBIT chunk into the file so that decoders can recover the original\ndata if desired.\n\n/* Set the true bit depth of the image data */\nif (colortype & PNGCOLORMASKCOLOR)\n{\nsigbit.red = truebitdepth;\nsigbit.green = truebitdepth;\nsigbit.blue = truebitdepth;\n}\n\nelse\n{\nsigbit.gray = truebitdepth;\n}\n\nif (colortype & PNGCOLORMASKALPHA)\n{\nsigbit.alpha = truebitdepth;\n}\n\npngsetsBIT(pngptr, infoptr, &sigbit);\n\nIf the data is stored in the row buffer in a bit depth other than one supported by PNG  (e.g.\n3  bit data in the range 0-7 for a 4-bit PNG), this will scale the values to appear to be the\ncorrect bit depth as is required by PNG.\n\npngsetshift(pngptr, &sigbit);\n\nPNG files store 16-bit pixels in network byte order (big-endian, ie.  most  significant  bits\nfirst).   This  code  would  be  used if they are supplied the other way (little-endian, i.e.\nleast significant bits first, the way PCs store them):\n\nif (bitdepth > 8)\npngsetswap(pngptr);\n\nIf you are using packed-pixel images (1, 2, or 4 bits/pixel), and you need to change the  or‐\nder the pixels are packed into bytes, you can use:\n\nif (bitdepth < 8)\npngsetpackswap(pngptr);\n\nPNG  files  store  3 color pixels in red, green, blue order.  This code would be used if they\nare supplied as blue, green, red:\n\npngsetbgr(pngptr);\n\nPNG files describe monochrome as black being zero and white being one.  This  code  would  be\nused if the pixels are supplied with this reversed (black being one and white being zero):\n\npngsetinvertmono(pngptr);\n\nFinally,  you  can  write your own transformation function if none of the existing ones meets\nyour needs.  This is done by setting a callback with\n\npngsetwriteusertransformfn(pngptr,\nwritetransformfn);\n\nYou must supply the function\n\nvoid writetransformfn(pngstructp pngptr, pngrowinfop\nrowinfo, pngbytep data)\n\nSee pngtest.c for a working example.  Your function will be called before any  of  the  other\ntransformations are processed.  If supported libpng also supplies an information routine that\nmay be called from your callback:\n\npnggetcurrentrownumber(pngptr);\npnggetcurrentpassnumber(pngptr);\n\nThis  returns  the current row passed to the transform.  With interlaced images the value re‐\nturned is the row in the input sub-image image.   Use  PNGROWFROMPASSROW(row,  pass)  and\nPNGCOLFROMPASSCOL(col, pass) to find the output pixel (x,y) given an interlaced sub-image\npixel (row,col,pass).\n\nThe discussion of interlace handling above contains more information on how to use these val‐\nues.\n\nYou can also set up a pointer to a user structure for use by your callback function.\n\npngsetusertransforminfo(pngptr, userptr, 0, 0);\n\nThe  userchannels  and  userdepth parameters of this function are ignored when writing; you\ncan set them to zero as shown.\n\nYou can retrieve the pointer via the function pnggetusertransformptr().  For example:\n\nvoidp writeusertransformptr =\npnggetusertransformptr(pngptr);\n\nIt is possible to have libpng flush any pending output, either manually, or automatically af‐\nter a certain number of lines have been written.  To flush the output stream  a  single  time\ncall:\n\npngwriteflush(pngptr);\n\nand  to  have libpng flush the output stream periodically after a certain number of scanlines\nhave been written, call:\n\npngsetflush(pngptr, nrows);\n\nNote that the distance between rows is from the last time pngwriteflush()  was  called,  or\nthe  first  row of the image if it has never been called.  So if you write 50 lines, and then\npngsetflush 25, it will flush the output on the next scanline, and every  25  lines  there‐\nafter,  unless  pngwriteflush() is called before 25 more lines have been written.  If nrows\nis too small (less than about 10 lines for a 640 pixel wide RGB image) the image  compression\nmay decrease noticeably (although this may be acceptable for real-time applications).  Infre‐\nquent  flushing  will  only  degrade the compression performance by a few percent over images\nthat do not use flushing.\n\n"
                },
                {
                    "name": "Writing the image data",
                    "content": "That's it for the transformations.  Now you can write the image data.  The simplest way to do\nthis is in one function call.  If you have the whole image  in  memory,  you  can  just  call\npngwriteimage()  and  libpng  will  write  the image.  You will need to pass in an array of\npointers to each row.  This function automatically handles interlacing, so you don't need  to\ncall  pngsetinterlacehandling() or call this function multiple times, or any of that other\nstuff necessary with pngwriterows().\n\npngwriteimage(pngptr, rowpointers);\n\nwhere rowpointers is:\n\npngbyte *rowpointers[height];\n\nYou can point to void or char or whatever you use for pixels.\n\nIf you don't want to write the whole image at once, you can use pngwriterows() instead.  If\nthe file is not interlaced, this is simple:\n\npngwriterows(pngptr, rowpointers,\nnumberofrows);\n\nrowpointers is the same as in the pngwriteimage() call.\n\nIf you are just writing one row at a time, you can do this with a single rowpointer  instead\nof an array of rowpointers:\n\npngbytep rowpointer = row;\n\npngwriterow(pngptr, rowpointer);\n\nWhen the file is interlaced, things can get a good deal more complicated.  The only currently\n(as of the PNG Specification version 1.2, dated July 1999) defined interlacing scheme for PNG\nfiles is the \"Adam7\" interlace scheme, that breaks down an image into seven smaller images of\nvarying  size.   libpng will build these images for you, or you can do them yourself.  If you\nwant to build them yourself, see the PNG specification for details of which pixels  to  write\nwhen.\n\nIf  you  don't want libpng to handle the interlacing details, just use pngsetinterlacehan‐\ndling() and call pngwriterows() the correct number of times to  write  all  the  sub-images\n(pngsetinterlacehandling() returns the number of sub-images.)\n\nIf you want libpng to build the sub-images, call this before you start writing any rows:\n\nnumberofpasses = pngsetinterlacehandling(pngptr);\n\nThis  will  return  the number of passes needed.  Currently, this is seven, but may change if\nanother interlace type is added.\n\nThen write the complete image numberofpasses times.\n\npngwriterows(pngptr, rowpointers, numberofrows);\n\nThink carefully before you write an interlaced image.  Typically code that reads such  images\nreads  all  the image data into memory, uncompressed, before doing any processing.  Only code\nthat can display an image on the fly can take advantage of the interlacing and even then  the\nimage  has to be exactly the correct size for the output device, because scaling an image re‐\nquires adjacent pixels and these are not available until all the passes have been read.\n\nIf you do write an interlaced image you will hardly ever need to handle the interlacing your‐\nself.  Call pngsetinterlacehandling() and use the approach described above.\n\nThe only time it is conceivable that you will really need to write an interlaced image  pass-\nby-pass is when you have read one pass by pass and made some pixel-by-pixel transformation to\nit,  as  described  in  the  read  code  above.   In  this  case  use  the  PNGPASSROWS and\nPNGPASSCOLS macros to determine the size of each sub-image in turn  and  simply  write  the\nrows you obtained from the read code.\n\n"
                },
                {
                    "name": "Finishing a sequential write",
                    "content": "After you are finished writing the image, you should finish writing the file.  If you are in‐\nterested  in  writing  comments  or  time,  you  should pass an appropriately filled pnginfo\npointer.  If you are not interested, you can pass NULL.\n\npngwriteend(pngptr, infoptr);\n\nWhen you are done, you can free all memory used by libpng like this:\n\npngdestroywritestruct(&pngptr, &infoptr);\n\nIt is also possible to individually free the infoptr members that point to  libpng-allocated\nstorage with the following function:\n\npngfreedata(pngptr, infoptr, mask, seq)\n\nmask  - identifies data to be freed, a mask\ncontaining the bitwise OR of one or\nmore of\nPNGFREEPLTE, PNGFREETRNS,\nPNGFREEHIST, PNGFREEICCP,\nPNGFREEPCAL, PNGFREEROWS,\nPNGFREESCAL, PNGFREESPLT,\nPNGFREETEXT, PNGFREEUNKN,\nor simply PNGFREEALL\n\nseq   - sequence number of item to be freed\n(-1 for all items)\n\nThis  function  may be safely called when the relevant storage has already been freed, or has\nnot yet been allocated, or was allocated by the user  and not by libpng,  and will  in  those\ncases do nothing.  The \"seq\" parameter is ignored if only one item of the selected data type,\nsuch  as  PLTE,  is allowed.  If \"seq\" is not -1, and multiple items are allowed for the data\ntype identified in the mask, such as text or sPLT, only the n'th item  in  the  structure  is\nfreed, where n is \"seq\".\n\nIf you allocated data such as a palette that you passed in to libpng with pngset*, you must\nnot free it until just before the call to pngdestroywritestruct().\n\nThe  default behavior is only to free data that was allocated internally by libpng.  This can\nbe changed, so that libpng will not free the data, or so that it will free data that was  al‐\nlocated  by  the user with pngmalloc() or pngcalloc() and passed in via a pngset*() func‐\ntion, with\n\npngdatafreer(pngptr, infoptr, freer, mask)\n\nfreer  - one of\nPNGDESTROYWILLFREEDATA\nPNGSETWILLFREEDATA\nPNGUSERWILLFREEDATA\n\nmask   - which data elements are affected\nsame choices as in pngfreedata()\n\nFor example, to transfer responsibility for some data from a read structure to a write struc‐\nture, you could use\n\npngdatafreer(readptr, readinfoptr,\nPNGUSERWILLFREEDATA,\nPNGFREEPLTE|PNGFREEtRNS|PNGFREEhIST)\n\npngdatafreer(writeptr, writeinfoptr,\nPNGDESTROYWILLFREEDATA,\nPNGFREEPLTE|PNGFREEtRNS|PNGFREEhIST)\n\nthereby briefly reassigning responsibility for freeing to the user but immediately afterwards\nreassigning it once more to the writedestroy function.  Having done this, it would  then  be\nsafe  to  destroy the read structure and continue to use the PLTE, tRNS, and hIST data in the\nwrite structure.\n\nThis function only affects data that has already been allocated.  You can call this  function\nbefore calling after the pngset*() functions to control whether the user or pngdestroy*()\nis  supposed  to  free  the  data.  When the user assumes responsibility for libpng-allocated\ndata, the application must use pngfree() to free it, and when the user  transfers  responsi‐\nbility  to  libpng for data that the user has allocated, the user must have used pngmalloc()\nor pngcalloc() to allocate it.\n\nIf you allocated textptr.text, textptr.lang, and textptr.translatedkeyword separately, do\nnot transfer responsibility for freeing textptr to  libpng,  because  when  libpng  fills  a\npngtext  structure  it  combines these members with the key member, and pngfreedata() will\nfree only textptr.key.  Similarly, if you transfer responsibility for free'ing textptr from\nlibpng to your application, your application must not separately free those members.   For  a\nmore compact example of writing a PNG image, see the file example.c.\n\n\nV. Simplified API\nThe  simplified API, which became available in libpng-1.6.0, hides the details of both libpng\nand the PNG file format itself.  It allows PNG files to be read into a very limited number of\nin-memory bitmap formats or to be written from the same formats.  If these formats do not ac‐\ncommodate your needs then you can, and should, use the more sophisticated APIs above -  these\nsupport  a  wide variety of in-memory formats and a wide variety of sophisticated transforma‐\ntions to those formats as well as a wide variety of APIs to manipulate ancillary information.\n\nTo read a PNG file using the simplified API:\n\n1) Declare a 'pngimage' structure (see below) on the stack, set the\nversion field to PNGIMAGEVERSION and the 'opaque' pointer to NULL\n(this is REQUIRED, your program may crash if you don't do it.)\n\n2) Call the appropriate pngimagebeginread... function.\n\n3) Set the pngimage 'format' member to the required sample format.\n\n4) Allocate a buffer for the image and, if required, the color-map.\n\n5) Call pngimagefinishread to read the image and, if required, the\ncolor-map into your buffers.\n\nThere are no restrictions on the format of the PNG input itself; all valid color  types,  bit\ndepths, and interlace methods are acceptable, and the input image is transformed as necessary\nto  the  requested in-memory format during the pngimagefinishread() step.  The only caveat\nis that if you request a color-mapped image from a PNG that is full-color  or  makes  complex\nuse  of an alpha channel the transformation is extremely lossy and the result may look terri‐\nble.\n\nTo write a PNG file using the simplified API:\n\n1) Declare a 'pngimage' structure on the stack and memset()\nit to all zero.\n\n2) Initialize the members of the structure that describe the\nimage, setting the 'format' member to the format of the\nimage samples.\n\n3) Call the appropriate pngimagewrite... function with a\npointer to the image and, if necessary, the color-map to write\nthe PNG data.\n\npngimage is a structure that describes the in-memory format of an image  when  it  is  being\nread  or  defines  the  in-memory format of an image that you need to write.  The \"pngimage\"\nstructure contains the following members:\n\npngcontrolp opaque  Initialize to NULL, free with pngimagefree\npnguint32  version Set to PNGIMAGEVERSION\npnguint32  width   Image width in pixels (columns)\npnguint32  height  Image height in pixels (rows)\npnguint32  format  Image format as defined below\npnguint32  flags   A bit mask containing informational flags\npnguint32  colormapentries; Number of entries in the color-map\npnguint32  warningorerror;\nchar         message[64];\n\nIn the event of an error or warning the \"warningorerror\" field will be set  to  a  non-zero\nvalue  and  the 'message' field will contain a ' ' terminated string with the libpng error or\nwarning message.  If both warnings and an error were encountered, only the error is recorded.\nIf there are multiple warnings, only the first one is recorded.\n\nThe upper 30 bits of the \"warningorerror\" value are reserved; the low two  bits  contain  a\ntwo bit code such that a value more than 1 indicates a failure in the API just called:\n\n0 - no warning or error\n1 - warning\n2 - error\n3 - error preceded by warning\n\nThe  pixels  (samples)  of the image have one to four channels whose components have original\nvalues in the range 0 to 1.0:\n\n1: A single gray or luminance channel (G).\n2: A gray/luminance channel and an alpha channel (GA).\n3: Three red, green, blue color channels (RGB).\n4: Three color channels and an alpha channel (RGBA).\n\nThe channels are encoded in one of two ways:\n\na) As a small integer, value 0..255, contained in a single byte.  For the alpha channel the\noriginal value is simply value/255.  For the color or luminance channels the value is encoded\naccording to the sRGB specification and matches the 8-bit format expected by typical  display\ndevices.\n\nThe color/gray channels are not scaled (pre-multiplied) by the alpha channel and are suitable\nfor passing to color management software.\n\nb)  As a value in the range 0..65535, contained in a 2-byte integer, in the native byte or‐\nder of the platform on which the application is running.  All channels can  be  converted  to\nthe original value by dividing by 65535; all channels are linear.  Color channels use the RGB\nencoding  (RGB  end-points)  of  the  sRGB specification.  This encoding is identified by the\nPNGFORMATFLAGLINEAR flag below.\n\nWhen the simplified API needs to convert between sRGB and linear colorspaces, the actual sRGB\ntransfer   curve   defined   in   the   sRGB    specification    (see    the    article    at\nhttps://en.wikipedia.org/wiki/SRGB) is used, not the gamma=1/2.2 approximation used elsewhere\nin libpng.\n\nWhen  an alpha channel is present it is expected to denote pixel coverage of the color or lu‐\nminance channels and is returned as an associated alpha channel: the color/gray channels  are\nscaled (pre-multiplied) by the alpha value.\n\nThe  samples are either contained directly in the image data, between 1 and 8 bytes per pixel\naccording to the encoding, or are held in a color-map indexed by bytes in the image data.  In\nthe case of a color-map the color-map entries are individual samples, encoded as  above,  and\nthe image data has one byte per pixel to select the relevant sample from the color-map.\n\nPNGFORMAT*\n\nThe #defines to be used in pngimage::format.  Each #define identifies a particular layout of\nchannel  data  and, if present, alpha values.  There are separate defines for each of the two\ncomponent encodings.\n\nA format is built up using single bit flag values.  All combinations are valid.  Formats  can\nbe  built  up  from  the flag values or you can use one of the predefined values below.  When\ntesting formats always use the FORMATFLAG macros to test for individual  features  -  future\nversions of the library may add new flags.\n\nWhen reading or writing color-mapped images the format should be set to the format of the en‐\ntries  in  the  color-map  then  pngimage{read,write}colormap  called to read or write the\ncolor-map and set the format  correctly  for  the  image  data.   Do  not  set  the  PNGFOR‐\nMATFLAGCOLORMAP bit directly!\n\nNOTE:  libpng  can be built with particular features disabled. If you see compiler errors be‐\ncause the definition of one of the following flags has been compiled out it is because libpng\ndoes not have the required support.  It is possible, however, for the libpng configuration to\nenable the format on just read or just write; in that case you may see an error at run  time.\nYou  can  guard  against  this by checking for the definition of the appropriate \"SUPPORTED\"\nmacro, one of:\n\nPNGSIMPLIFIED{READ,WRITE}{BGR,AFIRST}SUPPORTED\n\nPNGFORMATFLAGALPHA    format with an alpha channel\nPNGFORMATFLAGCOLOR    color format: otherwise grayscale\nPNGFORMATFLAGLINEAR   2-byte channels else 1-byte\nPNGFORMATFLAGCOLORMAP image data is color-mapped\nPNGFORMATFLAGBGR      BGR colors, else order is RGB\nPNGFORMATFLAGAFIRST   alpha channel comes first\n\nSupported formats are as follows.  Future versions of libpng may support  more  formats;  for\ncompatibility  with  older versions simply check if the format macro is defined using #ifdef.\nThese defines describe the in-memory layout of the components of the pixels of the image.\n\nFirst the single byte (sRGB) formats:\n\nPNGFORMATGRAY\nPNGFORMATGA\nPNGFORMATAG\nPNGFORMATRGB\nPNGFORMATBGR\nPNGFORMATRGBA\nPNGFORMATARGB\nPNGFORMATBGRA\nPNGFORMATABGR\n\nThen the linear 2-byte formats.  When naming these \"Y\" is used to indicate a luminance (gray)\nchannel.  The component order within the pixel is always the same - there is no provision for\nswapping the order of the components in the linear format.  The components are  16-bit  inte‐\ngers  in  the native byte order for your platform, and there is no provision for swapping the\nbytes to a different endian condition.\n\nPNGFORMATLINEARY\nPNGFORMATLINEARYALPHA\nPNGFORMATLINEARRGB\nPNGFORMATLINEARRGBALPHA\n\nWith color-mapped formats the image data is one byte for each pixel. The  byte  is  an  index\ninto the color-map which is formatted as above.  To obtain a color-mapped format it is suffi‐\ncient just to add the PNGFOMATFLAGCOLORMAP to one of the above definitions, or you can use\none of the definitions below.\n\nPNGFORMATRGBCOLORMAP\nPNGFORMATBGRCOLORMAP\nPNGFORMATRGBACOLORMAP\nPNGFORMATARGBCOLORMAP\nPNGFORMATBGRACOLORMAP\nPNGFORMATABGRCOLORMAP\n\nPNGIMAGE macros\n\nThese  are  convenience macros to derive information from a pngimage structure.  The PNGIM‐\nAGESAMPLE macros return values appropriate to the actual image sample values -  either  the\nentries in the color-map or the pixels in the image.  The PNGIMAGEPIXEL macros return cor‐\nresponding  values for the pixels and will always return 1 for color-mapped formats.  The re‐\nmaining macros return information about the rows in the image and the complete image.\n\nNOTE: All the macros that take a pngimage::format parameter are compile  time  constants  if\nthe format parameter is, itself, a constant.  Therefore these macros can be used in array de‐\nclarations  and case labels where required.  Similarly the macros are also pre-processor con‐\nstants (sizeof is not used) so they can be used in #if tests.\n\nPNGIMAGESAMPLECHANNELS(fmt)\nReturns the total number of channels in a given format: 1..4\n\nPNGIMAGESAMPLECOMPONENTSIZE(fmt)\nReturns the size in bytes of a single component of a pixel or color-map\nentry (as appropriate) in the image: 1 or 2.\n\nPNGIMAGESAMPLESIZE(fmt)\nThis is the size of the sample data for one sample.  If the image is\ncolor-mapped it is the size of one color-map entry (and image pixels are\none byte in size), otherwise it is the size of one image pixel.\n\nPNGIMAGEMAXIMUMCOLORMAPCOMPONENTS(fmt)\nThe maximum size of the color-map required by the format expressed in a\ncount of components.  This can be used to compile-time allocate a\ncolor-map:\n\npnguint16 colormap[PNGIMAGEMAXIMUMCOLORMAPCOMPONENTS(linearfmt)];\n\npngbyte colormap[PNGIMAGEMAXIMUMCOLORMAPCOMPONENTS(sRGBfmt)];\n\nAlternatively use the PNGIMAGECOLORMAPSIZE macro below to use the\ninformation from one of the pngimagebeginread APIs and dynamically\nallocate the required memory.\n\nPNGIMAGECOLORMAPSIZE(fmt)\nThe size of the color-map required by the format; this is the size of the\ncolor-map buffer passed to the pngimage{read,write}colormap APIs. It is\na fixed number determined by the format so can easily be allocated on the\nstack if necessary.\n\nCorresponding information about the pixels\n\nPNGIMAGEPIXELCHANNELS(fmt)\nThe number of separate channels (components) in a pixel; 1 for a\ncolor-mapped image.\n\nPNGIMAGEPIXELCOMPONENTSIZE(fmt)   The size, in bytes, of each component in a  pixel;  1\nfor a color-mapped\nimage.\n\nPNGIMAGEPIXELSIZE(fmt)\nThe size, in bytes, of a complete pixel; 1 for a color-mapped image.\n\nInformation about the whole row, or whole image\n\nPNGIMAGEROWSTRIDE(image)\nReturns the total number of components in a single row of the image; this\nis the minimum 'row stride', the minimum count of components between each\nrow.  For a color-mapped image this is the minimum number of bytes in a\nrow.\n\nIf you need the stride measured in bytes, rowstridebytes is\nPNGIMAGEROWSTRIDE(image) * PNGIMAGEPIXELCOMPONENTSIZE(fmt)\nplus any padding bytes that your application might need, for example\nto start the next row on a 4-byte boundary.\n\nPNGIMAGEBUFFERSIZE(image, rowstride)\nReturn the size, in bytes, of an image buffer given a pngimage and a row\nstride - the number of components to leave space for in each row.\n\nPNGIMAGESIZE(image)\nReturn the size, in bytes, of the image in memory given just a pngimage;\nthe row stride is the minimum stride required for the image.\n\nPNGIMAGECOLORMAPSIZE(image)\nReturn the size, in bytes, of the color-map of this image.  If the image\nformat is not a color-map format this will return a size sufficient for\n256 entries in the given format; check PNGFORMATFLAGCOLORMAP if\nyou don't want to allocate a color-map in this case.\n\nPNGIMAGEFLAG*\n\nFlags  containing  additional  information  about  the image are held in the 'flags' field of\npngimage.\n\nPNGIMAGEFLAGCOLORSPACENOTsRGB == 0x01\nThis indicates that the RGB values of the in-memory bitmap do not\ncorrespond to the red, green and blue end-points defined by sRGB.\n\nPNGIMAGEFLAGFAST == 0x02\nOn write emphasise speed over compression; the resultant PNG file will be\nlarger but will be produced significantly faster, particular for large\nimages.  Do not use this option for images which will be distributed, only\nused it when producing intermediate files that will be read back in\nrepeatedly.  For a typical 24-bit image the option will double the read\nspeed at the cost of increasing the image size by 25%, however for many\nmore compressible images the PNG file can be 10 times larger with only a\nslight speed gain.\n\nPNGIMAGEFLAG16BITsRGB == 0x04\nOn read if the image is a 16-bit per component image and there is no gAMA\nor sRGB chunk assume that the components are sRGB encoded.  Notice that\nimages output by the simplified API always have gamma information; setting\nthis flag only affects the interpretation of 16-bit images from an\nexternal source.  It is recommended that the application expose this flag\nto the user; the user can normally easily recognize the difference between\nlinear and sRGB encoding.  This flag has no effect on write - the data\npassed to the write APIs must have the correct encoding (as defined\nabove.)\n\nIf the flag is not set (the default) input 16-bit per component data is\nassumed to be linear.\n\nNOTE: the flag can only be set after the pngimagebeginread call,\nbecause that call initializes the 'flags' field.\n\nREAD APIs\n\nThe pngimage passed to the read APIs must have been initialized by setting\nthe pngcontrolp field 'opaque' to NULL (or, better, memset the whole thing.)\n\nint pngimagebeginreadfromfile( pngimagep image,\nconst char *filename)\n\nThe named file is opened for read and the image header\nis filled in from the PNG header in the file.\n\nint pngimagebeginreadfromstdio (pngimagep image,\nFILE* file)\n\nThe PNG header is read from the stdio FILE object.\n\nint pngimagebeginreadfrommemory(pngimagep image,\npngconstvoidp memory, sizet size)\n\nThe PNG header is read from the given memory buffer.\n\nint pngimagefinishread(pngimagep image,\npngcolorp background, void *buffer,\npngint32 rowstride, void *colormap));\n\nFinish reading the image into the supplied buffer and\nclean up the pngimage structure.\n\nrowstride is the step, in pngbyte or pnguint16 units\nas appropriate, between adjacent rows.  A positive stride\nindicates that the top-most row is first in the buffer -\nthe normal top-down arrangement.  A negative stride\nindicates that the bottom-most row is first in the buffer.\n\nbackground need only be supplied if an alpha channel must\nbe removed from a pngbyte format and the removal is to be\ndone by compositing on a solid color; otherwise it may be\nNULL and any composition will be done directly onto the\nbuffer.  The value is an sRGB color to use for the\nbackground, for grayscale output the green channel is used.\n\nFor linear output removing the alpha channel is always done\nby compositing on black.\n\nvoid pngimagefree(pngimagep image)\n\nFree any data allocated by libpng in image->opaque,\nsetting the pointer to NULL.  May be called at any time\nafter the structure is initialized.\n\nWhen the simplified API needs to convert between sRGB and linear colorspaces, the actual sRGB\ntransfer   curve   defined   in   the   sRGB    specification    (see    the    article    at\nhttps://en.wikipedia.org/wiki/SRGB) is used, not the gamma=1/2.2 approximation used elsewhere\nin libpng.\n\nWRITE APIS\n\nFor write you must initialize a pngimage structure to describe the image to be written:\n\nversion: must be set to PNGIMAGEVERSION\nopaque: must be initialized to NULL\nwidth: image width in pixels\nheight: image height in rows\nformat: the format of the data you wish to write\nflags: set to 0 unless one of the defined flags applies; set\nPNGIMAGEFLAGCOLORSPACENOTsRGB for color format images\nwhere the RGB values do not correspond to the colors in sRGB.\ncolormapentries: set to the number of entries in the color-map (0 to 256)\n\nint pngimagewritetofile, (pngimagep image,\nconst char *file, int convertto8bit, const void *buffer,\npngint32 rowstride, const void *colormap));\n\nWrite the image to the named file.\n\nint pngimagewritetomemory (pngimagep image, void *memory,\npngallocsizet * PNGRESTRICT memorybytes,\nint convertto8bit, const void *buffer, ptrdifft rowstride,\nconst void *colormap));\n\nWrite the image to memory.\n\nint pngimagewritetostdio(pngimagep image, FILE *file,\nint convertto8bit, const void *buffer,\npngint32 rowstride, const void *colormap)\n\nWrite the image to the given (FILE*).\n\nWith  all  write  APIs  if image is in one of the linear formats with (pnguint16) data then\nsetting convertto8bit will cause the output to be a (pngbyte) PNG gamma encoded according\nto the sRGB specification, otherwise a 16-bit linear encoded PNG file is written.\n\nWith all APIs rowstride is handled as in the read APIs - it is the spacing from one  row  to\nthe next in component sized units (float) and if negative indicates a bottom-up row layout in\nthe  buffer.   If  you pass zero, libpng will calculate the rowstride for you from the width\nand number of channels.\n\nNote that the write API does not support interlacing, sub-8-bit  pixels,  indexed  (paletted)\nimages, or most ancillary chunks.\n\n\nVI. Modifying/Customizing libpng\nThere are two issues here.  The first is changing how libpng does standard things like memory\nallocation,  input/output, and error handling.  The second deals with more complicated things\nlike adding new chunks, adding new transformations, and generally changing how libpng  works.\nBoth of those are compile-time issues; that is, they are generally determined at the time the\ncode  is  written,  and  there  is rarely a need to provide the user with a means of changing\nthem.\n\nMemory allocation, input/output, and error handling\n\nAll of the memory allocation, input/output, and error handling in libpng goes  through  call‐\nbacks  that are user-settable.  The default routines are in pngmem.c, pngrio.c, pngwio.c, and\npngerror.c, respectively.  To change these functions,  call  the  appropriate  pngset*fn()\nfunction.\n\nMemory  allocation  is done through the functions pngmalloc(), pngcalloc(), and pngfree().\nThe pngmalloc() and pngfree() functions currently just call the standard  C  functions  and\npngcalloc() calls pngmalloc() and then clears the newly allocated memory to zero; note that\npngcalloc(pngptr,  size)  is  not the same as the calloc(number, size) function provided by\nstdlib.h.  There is limited support for certain systems with segmented  memory  architectures\nand  the  types  of  pointers  declared by png.h match this; you will have to use appropriate\npointers in your application.  If you prefer to use a  different  method  of  allocating  and\nfreeing data, you can use pngcreatereadstruct2() or pngcreatewritestruct2() to regis‐\nter  your own functions as described above.  These functions also provide a void pointer that\ncan be retrieved via\n\nmemptr = pnggetmemptr(pngptr);\n\nYour replacement memory functions must have prototypes as follows:\n\npngvoidp mallocfn(pngstructp pngptr,\npngallocsizet size);\n\nvoid freefn(pngstructp pngptr, pngvoidp ptr);\n\nYour mallocfn() must return NULL in case of failure.  The pngmalloc()  function  will  nor‐\nmally  call  pngerror()  if it receives a NULL from the system memory allocator or from your\nreplacement mallocfn().\n\nYour freefn() will never be called with a NULL ptr, since  libpng's  pngfree()  checks  for\nNULL before calling freefn().\n\nInput/Output  in libpng is done through pngread() and pngwrite(), which currently just call\nfread()  and  fwrite().   The  FILE  *  is  stored  in  pngstruct  and  is  initialized  via\npnginitio().   If you wish to change the method of I/O, the library supplies callbacks that\nyou can set through the function pngsetreadfn() and pngsetwritefn() at  run  time,  in‐\nstead  of  calling  the  pnginitio() function.  These functions also provide a void pointer\nthat can be retrieved via the function pnggetioptr().  For example:\n\npngsetreadfn(pngstructp readptr,\nvoidp readioptr, pngrwptr readdatafn)\n\npngsetwritefn(pngstructp writeptr,\nvoidp writeioptr, pngrwptr writedatafn,\npngflushptr outputflushfn);\n\nvoidp readioptr = pnggetioptr(readptr);\nvoidp writeioptr = pnggetioptr(writeptr);\n\nThe replacement I/O functions must have prototypes as follows:\n\nvoid userreaddata(pngstructp pngptr,\npngbytep data, sizet length);\n\nvoid userwritedata(pngstructp pngptr,\npngbytep data, sizet length);\n\nvoid userflushdata(pngstructp pngptr);\n\nThe userreaddata() function is responsible for detecting and handling end-of-data errors.\n\nSupplying NULL for the read, write, or flush functions sets them back to using the default  C\nstream  functions,  which  expect  the  ioptr to point to a standard *FILE structure.  It is\nprobably a mistake to use NULL for one of writedatafn and outputflushfn but not  both  of\nthem,  unless  you have built libpng with PNGNOWRITEFLUSH defined.  It is an error to read\nfrom a write stream, and vice versa.\n\nError handling in libpng is done  through  pngerror()  and  pngwarning().   Errors  handled\nthrough  pngerror()  are  fatal, meaning that pngerror() should never return to its caller.\nCurrently, this is handled via setjmp() and longjmp() (unless you have compiled  libpng  with\nPNGNOSETJMP,  in which case it is handled via PNGABORT()), but you could change this to do\nthings like exit() if you should wish, as long as your function does not return.\n\nOn non-fatal errors, pngwarning() is called to print a warning message, and then control re‐\nturns to the calling code.  By default pngerror()  and  pngwarning()  print  a  message  on\nstderr  via  fprintf() unless the library is compiled with PNGNOCONSOLEIO defined (because\nyou don't want the messages) or PNGNOSTDIO defined (because fprintf() isn't available).  If\nyou wish to change the behavior of the error functions, you will need to set up your own mes‐\nsage callbacks.  These functions are normally supplied at the time  that  the  pngstruct  is\ncreated.   It  is also possible to redirect errors and warnings to your own replacement func‐\ntions after pngcreate*struct() has been called by calling:\n\npngseterrorfn(pngstructp pngptr,\npngvoidp errorptr, pngerrorptr errorfn,\npngerrorptr warningfn);\n\nIf NULL is supplied for either errorfn or warningfn, then the libpng default function  will\nbe used, calling fprintf() and/or longjmp() if a problem is encountered.  The replacement er‐\nror functions should have parameters as follows:\n\nvoid usererrorfn(pngstructp pngptr,\npngconstcharp errormsg);\n\nvoid userwarningfn(pngstructp pngptr,\npngconstcharp warningmsg);\n\nThen,  within  your  usererrorfn  or userwarningfn, you can retrieve the errorptr if you\nneed it, by calling\n\npngvoidp errorptr = pnggeterrorptr(pngptr);\n\nThe motivation behind using setjmp() and longjmp() is the C++ throw and catch exception  han‐\ndling  methods.  This makes the code much easier to write, as there is no need to check every\nreturn code of every function call.  However, there are some uncertainties about  the  status\nof  local  variables after a longjmp, so the user may want to be careful about doing anything\nafter setjmp returns non-zero besides returning itself.  Consult your compiler  documentation\nfor  more  details.   For an alternative approach, you may wish to use the \"cexcept\" facility\n(see https://cexcept.sourceforge.io/), which is illustrated in pngvalid.c and in  contrib/vi‐\nsupng.\n\nBeginning  in  libpng-1.4.0,  the  pngsetbenignerrors() API became available.  You can use\nthis to handle certain errors (normally handled as errors) as warnings.\n\npngsetbenignerrors (pngptr, int allowed);\n\nallowed: 0: treat pngbenignerror() as an error.\n1: treat pngbenignerror() as a warning.\n\nAs of libpng-1.6.0, the default condition is to treat benign errors as warnings while reading\nand as errors while writing.\n\n"
                },
                {
                    "name": "Custom chunks",
                    "content": "If you need to read or write custom chunks, you may need to get deeper into the libpng  code.\nThe  library  now has mechanisms for storing and writing chunks of unknown type; you can even\ndeclare callbacks for custom chunks.  However, this may not be good  enough  if  the  library\ncode  itself  needs  to  know  about interactions between your chunk and existing `intrinsic'\nchunks.\n\nIf you need to write a new intrinsic chunk, first read the PNG specification. Acquire a first\nlevel of understanding of how it works.  Pay particular attention to the  sections  that  de‐\nscribe  chunk  names,  and look at how other chunks were designed, so you can do things simi‐\nlarly.  Second, check out the sections of libpng that read and write chunks.  Try to  find  a\nchunk  that  is  similar to yours and use it as a template.  More details can be found in the\ncomments inside the code.  It is best to handle  private  or  unknown  chunks  in  a  generic\nmethod, via callback functions, instead of by modifying libpng functions. This is illustrated\nin  pngtest.c,  which  uses  a callback function to handle a private \"vpAg\" chunk and the new\n\"sTER\" chunk, which are both unknown to libpng.\n\nIf you wish to write your own transformation for the data, look through the part of the  code\nthat  does  the transformations, and check out some of the simpler ones to get an idea of how\nthey work.  Try to find a similar transformation to the one you want to add and copy  off  of\nit.  More details can be found in the comments inside the code itself.\n\n"
                },
                {
                    "name": "Configuring for gui/windowing platforms:",
                    "content": "You  will  need  to  write new error and warning functions that use the GUI interface, as de‐\nscribed previously, and set them to be the error and  warning  functions  at  the  time  that\npngcreate*struct()  is  called,  in order to have them available during the structure ini‐\ntialization.  They can be changed later via pngseterrorfn().  On some compilers,  you  may\nalso have to change the memory allocators (pngmalloc, etc.).\n\n"
                },
                {
                    "name": "Configuring zlib:",
                    "content": "There  are  special  functions  to  configure  the  compression.  Perhaps the most useful one\nchanges the compression level, which currently uses input compression values in the range 0 -\n9.  The library normally uses the default  compression  level  (ZDEFAULTCOMPRESSION  =  6).\nTests  have  shown  that  for a large majority of images, compression values in the range 3-6\ncompress nearly as well as higher levels, and do so much faster.  For online applications  it\nmay  be  desirable  to  have  maximum  speed (ZBESTSPEED = 1).  With versions of zlib after\nv0.99, you can also specify no compression (ZNOCOMPRESSION =  0),  but  this  would  create\nfiles  larger  than  just  storing  the raw bitmap.  You can specify the compression level by\ncalling:\n\n#include zlib.h\npngsetcompressionlevel(pngptr, level);\n\nAnother useful one is to reduce the memory level used by the library.  The memory  level  de‐\nfaults  to  8,  but  it  can be lowered if you are short on memory (running DOS, for example,\nwhere you only have 640K).  Note that the memory level does have an  effect  on  compression;\namong other things, lower levels will result in sections of incompressible data being emitted\nin smaller stored blocks, with a correspondingly larger relative overhead of up to 15% in the\nworst case.\n\n#include zlib.h\npngsetcompressionmemlevel(pngptr, level);\n\nThe  other  functions  are for configuring zlib.  They are not recommended for normal use and\nmay result in writing an invalid PNG file.  See zlib.h for more  information  on  what  these\nmean.\n\n#include zlib.h\npngsetcompressionstrategy(pngptr,\nstrategy);\n\npngsetcompressionwindowbits(pngptr,\nwindowbits);\n\npngsetcompressionmethod(pngptr, method);\n\nThis controls the size of the IDAT chunks (default 8192):\n\npngsetcompressionbuffersize(pngptr, size);\n\nAs of libpng version 1.5.4, additional APIs became available to set these separately for non-\nIDAT compressed chunks such as zTXt, iTXt, and iCCP:\n\n#include zlib.h\n#if PNGLIBPNGVER >= 10504\npngsettextcompressionlevel(pngptr, level);\n\npngsettextcompressionmemlevel(pngptr, level);\n\npngsettextcompressionstrategy(pngptr,\nstrategy);\n\npngsettextcompressionwindowbits(pngptr,\nwindowbits);\n\npngsettextcompressionmethod(pngptr, method);\n#endif\n\n"
                },
                {
                    "name": "Controlling row filtering",
                    "content": "If  you want to control whether libpng uses filtering or not, which filters are used, and how\nit goes about picking row filters, you can call one of these functions.   The  selection  and\nconfiguration of row filters can have a significant impact on the size and encoding speed and\na  somewhat lesser impact on the decoding speed of an image.  Filtering is enabled by default\nfor RGB and grayscale images (with and without alpha), but not for paletted  images  nor  for\nany images with bit depths less than 8 bits/pixel.\n\nThe 'method' parameter sets the main filtering method, which is currently only '0' in the PNG\n1.2  specification.  The 'filters' parameter sets which filter(s), if any, should be used for\neach scanline.  Possible values are PNGALLFILTERS, PNGNOFILTERS, or  PNGFASTFILTERS  to\nturn  filtering  on  and off, or to turn on just the fast-decoding subset of filters, respec‐\ntively.\n\nIndividual filter types are PNGFILTERNONE, PNGFILTERSUB,  PNGFILTERUP,  PNGFILTERAVG,\nPNGFILTERPAETH,  which can be bitwise ORed together with '|' to specify one or more filters\nto use.  These filters are described in more detail in the PNG specification.  If you  intend\nto change the filter type during the course of writing the image, you should start with flags\nset  for  all  of  the  filters  you intend to use so that libpng can initialize its internal\nstructures appropriately for all of the filter types.  (Note that this means  the  first  row\nmust  always  be  adaptively  filtered, because libpng currently does not allocate the filter\nbuffers until pngwriterow() is called for the first time.)\n\nfilters = PNGNOFILTERS;\nfilters = PNGALLFILTERS;\nfilters = PNGFASTFILTERS;\n\nor\n\nfilters = PNGFILTERNONE | PNGFILTERSUB |\nPNGFILTERUP | PNGFILTERAVG |\nPNGFILTERPAETH;\n\npngsetfilter(pngptr, PNGFILTERTYPEBASE,\nfilters);\n\nThe second parameter can also be\nPNGINTRAPIXELDIFFERENCING if you are\nwriting a PNG to be embedded in a MNG\ndatastream.  This parameter must be the\nsame as the value of filtermethod used\nin pngsetIHDR().\n\n"
                },
                {
                    "name": "Requesting debug printout",
                    "content": "The macro definition PNGDEBUG can be used to request debugging printout.  Set it to an inte‐\nger value in the range 0 to 3.  Higher numbers result in increasing amounts of debugging  in‐\nformation.   The  information  is  printed  to the \"stderr\" file, unless another file name is\nspecified in the PNGDEBUGFILE macro definition.\n\nWhen PNGDEBUG > 0, the following functions (macros) become available:\n\npngdebug(level, message)\npngdebug1(level, message, p1)\npngdebug2(level, message, p1, p2)\n\nin which \"level\" is compared to PNGDEBUG to decide whether to print the  message,  \"message\"\nis  the  formatted string to be printed, and p1 and p2 are parameters that are to be embedded\nin the string according to printf-style formatting directives.  For example,\n\npngdebug1(2, \"foo=%d\", foo);\n\nis expanded to\n\nif (PNGDEBUG > 2)\nfprintf(PNGDEBUGFILE, \"foo=%d\\n\", foo);\n\nWhen PNGDEBUG is defined but is zero, the macros aren't  defined,  but  you  can  still  use\nPNGDEBUG to control your own debugging:\n\n#ifdef PNGDEBUG\nfprintf(stderr, ...);\n#endif\n\nWhen  PNGDEBUG  =  1, the macros are defined, but only pngdebug statements having level = 0\nwill be printed.  There aren't any such statements in this version of libpng, but if you  in‐\nsert some they will be printed.\n\n\nVII. MNG support\nThe  MNG specification (available at http://www.libpng.org/pub/mng) allows certain extensions\nto PNG for PNG images that are embedded in MNG datastreams.  Libpng can support some of these\nextensions.  To enable them, use the pngpermitmngfeatures() function:\n\nfeatureset = pngpermitmngfeatures(pngptr, mask)\n\nmask is a pnguint32 containing the bitwise OR of the\nfeatures you want to enable.  These include\nPNGFLAGMNGEMPTYPLTE\nPNGFLAGMNGFILTER64\nPNGALLMNGFEATURES\n\nfeatureset is a pnguint32 that is the bitwise AND of\nyour mask with the set of MNG features that is\nsupported by the version of libpng that you are using.\n\nIt is an error to use this function when reading or writing a standalone PNG  file  with  the\nPNG 8-byte signature.  The PNG datastream must be wrapped in a MNG datastream.  As a minimum,\nit  must have the MNG 8-byte signature and the MHDR and MEND chunks.  Libpng does not provide\nsupport for these or any other MNG chunks; your application must provide its own support  for\nthem.  You may wish to consider using libmng (available at https://www.libmng.com/) instead.\n\n\nVIII. Changes to Libpng from version 0.88\nIt  should be noted that versions of libpng later than 0.96 are not distributed by the origi‐\nnal libpng author, Guy Schalnat, nor by Andreas Dilger, who had taken over  from  Guy  during\n1996  and  1997,  and distributed versions 0.89 through 0.96, but rather by another member of\nthe original PNG Group, Glenn Randers-Pehrson.  Guy and Andreas are still alive and well, but\nthey have moved on to other things.\n\nThe old libpng functions  pngreadinit(),  pngwriteinit(),  pnginfoinit(),  pngreadde‐\nstroy(),  and pngwritedestroy() have been moved to PNGINTERNAL in version 0.95 to discour‐\nage their use.  These functions will be removed from libpng version 1.4.0.\n\nThe preferred method of creating and initializing the libpng structures is via  the  pngcre‐\natereadstruct(),  pngcreatewritestruct(), and pngcreateinfostruct() because they iso‐\nlate the size of the structures from the application, allow version error checking, and  also\nallow  the  use  of  custom  error handling routines during the initialization, which the old\nfunctions do not.  The functions pngreaddestroy() and pngwritedestroy() do  not  actually\nfree  the memory that libpng allocated for these structs, but just reset the data structures,\nso they can be used instead of pngdestroyreadstruct()  and  pngdestroywritestruct()  if\nyou feel there is too much system overhead allocating and freeing the pngstruct for each im‐\nage read.\n\nSetting  the error callbacks via pngsetmessagefn() before pngreadinit() as was suggested\nin libpng-0.88 is no longer supported because this caused applications that do not use custom\nerror functions to fail if the pngptr was not initialized to zero.  It is still possible  to\nset  the  error  callbacks  AFTER pngreadinit(), or to change them with pngseterrorfn(),\nwhich is essentially the same function, but with a new name to force compilation errors  with\napplications that try to use the old method.\n\nSupport  for  the  sCAL, iCCP, iTXt, and sPLT chunks was added at libpng-1.0.6; however, iTXt\nsupport was not enabled by default.\n\nStarting with version 1.0.7, you can find out which version of the library you are  using  at\nrun-time:\n\npnguint32 libpngvn = pngaccessversionnumber();\n\nThe  number libpngvn is constructed from the major version, minor version with leading zero,\nand release number with leading zero, (e.g., libpngvn for version 1.0.7 is 10007).\n\nNote that this function does not take a pngptr, so you can call  it  before  you've  created\none.\n\nYou can also check which version of png.h you used when compiling your application:\n\npnguint32 applicationvn = PNGLIBPNGVER;\n\n\nIX. Changes to Libpng from version 1.0.x to 1.2.x\nSupport for user memory management was enabled by default.  To accomplish this, the functions\npngcreatereadstruct2(), pngcreatewritestruct2(), pngsetmemfn(), pnggetmemptr(),\npngmallocdefault(), and pngfreedefault() were added.\n\nSupport for the iTXt chunk has been enabled by default as of version 1.2.41.\n\nSupport for certain MNG features was enabled.\n\nSupport for numbered error messages was added.  However, we never got around to actually num‐\nbering  the  error messages.  The function pngsetstriperrornumbers() was added (Note: the\nprototype for this function was inadvertently removed  from  png.h  in  PNGNOASSEMBLERCODE\nbuilds of libpng-1.2.15.  It was restored in libpng-1.2.36).\n\nThe  pngmallocwarn() function was added at libpng-1.2.3.  This issues a pngwarning and re‐\nturns NULL instead of aborting when it fails to acquire the requested memory allocation.\n\nSupport for setting user limits on image width and height was enabled by default.  The  func‐\ntions  pngsetuserlimits(),  pnggetuserwidthmax(),  and  pnggetuserheightmax() were\nadded at libpng-1.2.6.\n\nThe pngsetaddalpha() function was added at libpng-1.2.7.\n\nThe  function   pngsetexpandgray124to8()   was   added   at   libpng-1.2.9.    Unlike\npngsetgray124to8(),  the  new  function  does  not expand the tRNS chunk to alpha. The\npngsetgray124to8() function is deprecated.\n\nA number of macro definitions in support of runtime selection of assembler code features (es‐\npecially Intel MMX code support) were added at libpng-1.2.0:\n\nPNGASMFLAGMMXSUPPORTCOMPILED\nPNGASMFLAGMMXSUPPORTINCPU\nPNGASMFLAGMMXREADCOMBINEROW\nPNGASMFLAGMMXREADINTERLACE\nPNGASMFLAGMMXREADFILTERSUB\nPNGASMFLAGMMXREADFILTERUP\nPNGASMFLAGMMXREADFILTERAVG\nPNGASMFLAGMMXREADFILTERPAETH\nPNGASMFLAGSINITIALIZED\nPNGMMXREADFLAGS\nPNGMMXFLAGS\nPNGMMXWRITEFLAGS\nPNGMMXFLAGS\n\nWe added the following functions in support of runtime selection of assembler code features:\n\npnggetmmxflagmask()\npngsetmmxthresholds()\npnggetasmflags()\npnggetmmxbitdepththreshold()\npnggetmmxrowbytesthreshold()\npngsetasmflags()\n\nWe replaced all of these functions with simple stubs in libpng-1.2.20, when the Intel  assem‐\nbler code was removed due to a licensing issue.\n\nThese macros are deprecated:\n\nPNGREADTRANSFORMSNOTSUPPORTED\nPNGPROGRESSIVEREADNOTSUPPORTED\nPNGNOSEQUENTIALREADSUPPORTED\nPNGWRITETRANSFORMSNOTSUPPORTED\nPNGREADANCILLARYCHUNKSNOTSUPPORTED\nPNGWRITEANCILLARYCHUNKSNOTSUPPORTED\n\nThey have been replaced, respectively, by:\n\nPNGNOREADTRANSFORMS\nPNGNOPROGRESSIVEREAD\nPNGNOSEQUENTIALREAD\nPNGNOWRITETRANSFORMS\nPNGNOREADANCILLARYCHUNKS\nPNGNOWRITEANCILLARYCHUNKS\n\nPNGMAXUINT  was  replaced with PNGUINT31MAX.  It has been deprecated since libpng-1.0.16\nand libpng-1.2.6.\n\nThe function\npngchecksig(sig, num) was replaced with\npngsigcmp(sig, 0, num) == 0 It has been deprecated since libpng-0.90.\n\nThe function\npngsetgray124to8() which also expands tRNS to alpha was replaced with\npngsetexpandgray124to8()  which  does  not.  It   has   been   deprecated   since\nlibpng-1.0.18 and 1.2.9.\n\n\nX. Changes to Libpng from version 1.0.x/1.2.x to 1.4.x\nPrivate  libpng  prototypes  and macro definitions were moved from png.h and pngconf.h into a\nnew pngpriv.h header file.\n\nFunctions  pngsetbenignerrors(),  pngbenignerror(),  and  pngchunkbenignerror()  were\nadded.\n\nSupport for setting the maximum amount of memory that the application will allocate for read‐\ning  chunks  was  added,  as a security measure.  The functions pngsetchunkcachemax() and\npnggetchunkcachemax() were added to the library.\n\nWe implemented support for I/O  states  by  adding  pngptr  member  iostate  and  functions\npnggetiochunkname() and pnggetiostate() in pngget.c\n\nWe added PNGTRANSFORMGRAYTORGB to the available high-level input transforms.\n\nChecking for and reporting of errors in the IHDR chunk is more thorough.\n\nSupport for global arrays was removed, to improve thread safety.\n\nSome obsolete/deprecated macros and functions have been removed.\n\nTypecasted NULL definitions such as\n#define  pngvoidpNULL             (pngvoidp)NULL were eliminated.  If you used these in\nyour application, just use NULL instead.\n\nThe pngstruct and infostruct members \"trans\" and \"transvalues\" were changed to  \"transal‐\npha\" and \"transcolor\", respectively.\n\nThe obsolete, unused pnggccrd.c and pngvcrd.c files and related makefiles were removed.\n\nThe PNG10X and PNG12X macros were eliminated.\n\nThe PNGLEGACYSUPPORTED macro was eliminated.\n\nMany WIN32WCE #ifdefs were removed.\n\nThe  functions  pngreadinit(infoptr),  pngwriteinit(infoptr),  pnginfoinit(infoptr),\npngreaddestroy(), and pngwritedestroy() have been removed.   They  have  been  deprecated\nsince libpng-0.95.\n\nThe  pngpermitemptyplte()  was  removed.  It  has been deprecated since libpng-1.0.9.  Use\npngpermitmngfeatures() instead.\n\nWe removed the  obsolete  stub  functions  pnggetmmxflagmask(),  pngsetmmxthresholds(),\npnggetasmflags(),    pnggetmmxbitdepththreshold(),   pnggetmmxrowbytesthreshold(),\npngsetasmflags(), and pngmmxsupported()\n\nWe removed the obsolete pngchecksig(),  pngmemcpycheck(),  and  pngmemsetcheck()  func‐\ntions.  Instead use pngsigcmp() == 0, memcpy(), and memset(), respectively.\n\nThe   function   pngsetgray124to8()   was   removed.  It  has  been  deprecated  since\nlibpng-1.0.18 and 1.2.9, when it was replaced with  pngsetexpandgray124to8()  because\nthe former function also expanded any tRNS chunk to an alpha channel.\n\nMacros  for  pnggetuint16,  pnggetuint32, and pnggetint32 were added and are used by\ndefault instead of the corresponding functions. Unfortunately, from libpng-1.4.0 until 1.4.4,\nthe pnggetuint16 macro (but not  the  function)  incorrectly  returned  a  value  of  type\npnguint32.\n\nWe changed the prototype for pngmalloc() from\npngmalloc(pngstructp pngptr, pnguint32 size) to\npngmalloc(pngstructp pngptr, pngallocsizet size)\n\nThis also applies to the prototype for the user replacement mallocfn().\n\nThe  pngcalloc() function was added and is used in place of of \"pngmalloc(); memset();\" ex‐\ncept in the case in pngreadpng() where the array consists of pointers; in this case a \"for\"\nloop is used after the pngmalloc() to set the pointers to NULL, to give robust.  behavior in\ncase the application runs out of memory part-way through the process.\n\nWe  changed  the  prototypes  of   pnggetcompressionbuffersize()   and   pngsetcompres‐\nsionbuffersize() to work with sizet instead of pnguint32.\n\nSupport  for numbered error messages was removed by default, since we never got around to ac‐\ntually numbering the error messages. The function pngsetstriperrornumbers()  was  removed\nfrom the library by default.\n\nThe pngzalloc() and pngzfree() functions are no longer exported.  The pngzalloc() function\nno  longer  zeroes  out  the  memory  that  it  allocates.  Applications that called pngzal‐\nloc(pngptr, number, size) can call pngcalloc(pngptr, number*size) instead,  and  can  call\npngfree() instead of pngzfree().\n\nSupport  for  dithering was disabled by default in libpng-1.4.0, because it has not been well\ntested and doesn't actually \"dither\".  The code was not removed, however, and  could  be  en‐\nabled  by building libpng with PNGREADDITHERSUPPORTED defined.  In libpng-1.4.2, this sup‐\nport was re-enabled, but the function was renamed pngsetquantize() to  reflect  more  accu‐\nrately  what it actually does.  At the same time, the PNGDITHER[RED,GREENBLUE]BITS macros\nwere also renamed to PNGQUANTIZE[RED,GREEN,BLUE]BITS,  and  PNGREADDITHERSUPPORTED  was\nrenamed to PNGREADQUANTIZESUPPORTED.\n\nWe removed the trailing '.' from the warning and error messages.\n\n\nXI. Changes to Libpng from version 1.4.x to 1.5.x\nFrom  libpng-1.4.0  until 1.4.4, the pnggetuint16 macro (but not the function) incorrectly\nreturned a value of type pnguint32.  The incorrect macro was removed from libpng-1.4.5.\n\nChecking for invalid palette index on write was added at libpng 1.5.10.  If a pixel  contains\nan invalid (out-of-range) index libpng issues a benign error.  This is enabled by default be‐\ncause  this  condition is an error according to the PNG specification, Clause 11.3.2, but the\nerror can be ignored in each pngptr with\n\npngsetcheckforinvalidindex(pngptr, allowed);\n\nallowed  - one of\n0: disable benign error (accept the\ninvalid data without warning).\n1: enable benign error (treat the\ninvalid data as an error or a\nwarning).\n\nIf the error is ignored, or if pngbenignerror() treats it as a warning, any invalid  pixels\nare decoded as opaque black by the decoder and written as-is by the encoder.\n\nRetrieving  the  maximum palette index found was added at libpng-1.5.15.  This statement must\nappear after pngreadpng() or pngreadimage() while reading, and after  pngwritepng()  or\npngwriteimage() while writing.\n\nint maxpalette = pnggetpalettemax(pngptr, infoptr);\n\nThis will return the maximum palette index found in the image, or \"-1\" if the palette was not\nchecked, or \"0\" if no palette was found.  Note that this does not account for any palette in‐\ndex  used  by ancillary chunks such as the bKGD chunk; you must check those separately to de‐\ntermine the maximum palette index actually used.\n\nThere are no substantial API changes between the non-deprecated parts of the  1.4.5  API  and\nthe  1.5.0  API;  however,  the ability to directly access members of the main libpng control\nstructures, pngstruct and pnginfo, deprecated in earlier versions of libpng, has been  com‐\npletely removed from libpng 1.5, and new private \"pngstruct.h\", \"pnginfo.h\", and \"pngdebug.h\"\nheader files were created.\n\nWe  no  longer include zlib.h in png.h.  The include statement has been moved to pngstruct.h,\nwhere it is not accessible by applications. Applications that need access to  information  in\nzlib.h  will  need to add the '#include \"zlib.h\"' directive.  It does not matter whether this\nis placed prior to or after the '\"#include png.h\"' directive.\n\nThe pngsprintf(), pngstrcpy(), and pngstrncpy() macros are no longer  used  and  were  re‐\nmoved.\n\nWe moved the pngstrlen(), pngmemcpy(), pngmemset(), and pngmemcmp() macros into a private\nheader file (pngpriv.h) that is not accessible to applications.\n\nIn  pnggetiCCP,  the  type  of  \"profile\" was changed from pngcharpp to pngbytepp, and in\npngsetiCCP, from pngcharp to pngconstbytep.\n\nThere are changes of form in png.h, including new and changed macros to declare parts of  the\nAPI.   Some  API  functions  with arguments that are pointers to data not modified within the\nfunction have been corrected to declare these arguments with const.\n\nMuch of the internal use of C macros to control the library build has also changed  and  some\nof  this  is visible in the exported header files, in particular the use of macros to control\ndata and API elements visible during application compilation may require significant revision\nto application code.  (It is extremely rare for an application to do this.)\n\nAny program that compiled against libpng 1.4 and did not use deprecated  features  or  access\ninternal library structures should compile and work against libpng 1.5, except for the change\nin the prototype for pnggetiCCP() and pngsetiCCP() API functions mentioned above.\n\nlibpng  1.5.0  adds PNG PASS macros to help in the reading and writing of interlaced images.\nThe macros return the number of rows and columns in each pass and  information  that  can  be\nused to de-interlace and (if absolutely necessary) interlace an image.\n\nlibpng  1.5.0  adds  an API pnglongjmp(pngptr, value).  This API calls the application-pro‐\nvided pnglongjmpptr on the internal, but application initialized, longjmp  buffer.   It  is\nprovided as a convenience to avoid the need to use the pngjmpbuf macro, which had the unnec‐\nessary side effect of resetting the internal pnglongjmpptr value.\n\nlibpng  1.5.0 includes a complete fixed point API.  By default this is present along with the\ncorresponding floating point API.  In general the fixed point API is faster and smaller  than\nthe  floating  point  one  because  the PNG file format used fixed point, not floating point.\nThis applies even if the library uses floating point in internal calculations.  A new  macro,\nPNGFLOATINGARITHMETICSUPPORTED, reveals whether the library uses floating point arithmetic\n(the default) or fixed point arithmetic internally for performance critical calculations such\nas  gamma  correction.   In some cases, the gamma calculations may produce slightly different\nresults.   This  has  changed  the  results  in  pngrgbtogray  and  in  alpha  composition\n(pngsetbackground  for example). This applies even if the original image was already linear\n(gamma == 1.0) and, therefore, it is not necessary to linearize the image.  This  is  because\nlibpng has *not* been changed to optimize that case correctly, yet.\n\nFixed point support for the sCAL chunk comes with an important caveat; the sCAL specification\nuses  a  decimal encoding of floating point values and the accuracy of PNG fixed point values\nis  insufficient  for  representation  of  these  values.   Consequently   a   \"string\"   API\n(pnggetsCALs and pngsetsCALs) is the only reliable way of reading arbitrary sCAL chunks\nin  the  absence  of  either  the floating point API or internal floating point calculations.\nStarting with libpng-1.5.0, both of these functions are present  when  PNGsCALSUPPORTED  is\ndefined.   Prior to libpng-1.5.0, their presence also depended upon PNGFIXEDPOINTSUPPORTED\nbeing defined and PNGFLOATINGPOINTSUPPORTED not being defined.\n\nApplications no longer need to include the optional distribution header file pngusr.h or  de‐\nfine the corresponding macros during application build in order to see the correct variant of\nthe  libpng  API.   From  1.5.0  application  code can check for the corresponding SUPPORTED\nmacro:\n\n#ifdef PNGINCHCONVERSIONSSUPPORTED\n/* code that uses the inch conversion APIs. */ #endif\n\nThis macro will only be defined if the inch conversion  functions  have  been  compiled  into\nlibpng.   The full set of macros, and whether or not support has been compiled in, are avail‐\nable in the header file pnglibconf.h.  This header file is specific to the libpng build.  No‐\ntice that prior to 1.5.0 the SUPPORTED macros would always have the default  definition  un‐\nless  reset by pngusr.h or by explicit settings on the compiler command line.  These settings\nmay produce compiler warnings or errors in 1.5.0 because of macro redefinition.\n\nApplications can now choose whether to use these macros or to call the corresponding function\nby defining PNGUSEREADMACROS or PNGNOUSEREADMACROS  before  including  png.h.   Notice\nthat  this  is only supported from 1.5.0; defining PNGNOUSEREADMACROS prior to 1.5.0 will\nlead to a link failure.\n\nPrior to libpng-1.5.4, the zlib compressor used the same set of parameters  when  compressing\nthe  IDAT  data and textual data such as zTXt and iCCP.  In libpng-1.5.4 we reinitialized the\nzlib stream for each type of data.  We added five pngsettext*() functions for setting  the\nparameters to use with textual data.\n\nPrior  to  libpng-1.5.4,  the PNGREAD16TO8ACCURATESCALESUPPORTED option was off by de‐\nfault, and slightly inaccurate scaling occurred.  This option can no longer  be  turned  off,\nand   the   choice   of   accurate  or  inaccurate  16-to-8  scaling  is  by  using  the  new\npngsetscale16to8() API for accurate scaling or the old pngsetstrip16to8()  API  for\nsimple chopping.  In libpng-1.5.4, the PNGREAD16TO8ACCURATESCALESUPPORTED macro became\nPNGREADSCALE16TO8SUPPORTED,      and      the     PNGREAD16TO8     macro     became\nPNGREADSTRIP16TO8SUPPORTED, to enable the two pngset*16to8() functions separately.\n\nPrior to libpng-1.5.4, the pngsetuserlimits() function could only be used  to  reduce  the\nwidth  and  height  limits  from the value of PNGUSERWIDTHMAX and PNGUSERHEIGHTMAX, al‐\nthough this document said that it could be used to override them.  Now this function will re‐\nduce or increase the limits.\n\nStarting in libpng-1.5.22, default user limits were established. These can be  overridden  by\napplication    calls   to   pngsetuserlimits(),   pngsetuserchunkcachemax(),   and/or\npngsetusermallocmax().  The limits are now\nmax possible  default\npnguserwidthmax        0x7fffffff    1,000,000\npnguserheightmax       0x7fffffff    1,000,000\npnguserchunkcachemax  0 (unlimited) 1000\npnguserchunkmallocmax 0 (unlimited) 8,000,000\n\nThe pngsetoption() function (and the \"options\" member of  the  png  struct)  was  added  to\nlibpng-1.5.15, with option PNGARMNEON.\n\nThe  library  now supports a complete fixed point implementation and can thus be used on sys‐\ntems that have no floating point support or very limited or slow support.   Previously  gamma\ncorrection,  an  essential  part  of  complete PNG support, required reasonably fast floating\npoint.\n\nAs part of this the choice of internal implementation has been made independent of the choice\nof fixed versus floating point APIs and all the missing fixed point  APIs  have  been  imple‐\nmented.\n\nThe  exact mechanism used to control attributes of API functions has changed, as described in\nthe INSTALL file.\n\nA new test program, pngvalid, is provided in addition to  pngtest.   pngvalid  validates  the\narithmetic accuracy of the gamma correction calculations and includes a number of validations\nof the file format.  A subset of the full range of tests is run when \"make check\" is done (in\nthe  'configure'  build.)   pngvalid also allows total allocated memory usage to be evaluated\nand performs additional memory overwrite validation.\n\nMany changes to individual feature macros have been made. The following are the changes  most\nlikely to be noticed by library builders who configure libpng:\n\n1) All feature macros now have consistent naming:\n\n#define  PNGNOfeature turns the feature off #define PNGfeatureSUPPORTED turns the feature\non\n\npnglibconf.h contains one line for each feature macro which is either:\n\n#define PNGfeatureSUPPORTED\n\nif the feature is supported or:\n\n/*#undef PNGfeatureSUPPORTED*/\n\nif it is not.  Library code consistently checks for the 'SUPPORTED' macro.  It does not,  and\nlibpng  applications  should not, check for the 'NO' macro which will not normally be defined\neven if the feature is not supported.  The 'NO' macros are only used internally  for  setting\nor not setting the corresponding 'SUPPORTED' macros.\n\nCompatibility with the old names is provided as follows:\n\nPNGINCHCONVERSIONS turns on PNGINCHCONVERSIONSSUPPORTED\n\nAnd the following definitions disable the corresponding feature:\n\nPNGSETJMPNOTSUPPORTED    disables    SETJMP   PNGREADTRANSFORMSNOTSUPPORTED   disables\nREADTRANSFORMS PNGNOREADCOMPOSITEDNODIV disables  READCOMPOSITENODIV  PNGWRITETRANS‐\nFORMSNOTSUPPORTED  disables  WRITETRANSFORMS  PNGREADANCILLARYCHUNKSNOTSUPPORTED dis‐\nables READANCILLARYCHUNKS  PNGWRITEANCILLARYCHUNKSNOTSUPPORTED  disables  WRITEANCIL‐\nLARYCHUNKS\n\nLibrary builders should remove use of the above, inconsistent, names.\n\n2)  Warning and error message formatting was previously conditional on the STDIO feature. The\nlibrary has been changed to use the CONSOLEIO feature instead. This means that if CONSOLEIO\nis disabled the library no longer uses the  printf(3)  functions,  even  though  the  default\nread/write implementations use (FILE) style stdio.h functions.\n\n3) Three feature macros now control the fixed/floating point decisions:\n\nPNGFLOATINGPOINTSUPPORTED enables the floating point APIs\n\nPNGFIXEDPOINTSUPPORTED  enables  the fixed point APIs; however, in practice these are nor‐\nmally required internally anyway (because the PNG file format is fixed point),  therefore  in\nmost cases PNGNOFIXEDPOINT merely stops the function from being exported.\n\nPNGFLOATINGARITHMETICSUPPORTED  chooses between the internal floating point implementation\nor the fixed point one.  Typically the fixed point implementation is larger and  slower  than\nthe  floating  point implementation on a system that supports floating point; however, it may\nbe faster on a system which lacks floating point hardware and therefore uses a software  emu‐\nlation.\n\n4)  Added  PNG{READ,WRITE}INTFUNCTIONSSUPPORTED.   This  allows the functions to read and\nwrite ints to be disabled independently of PNGUSEREADMACROS, which  allows  libpng  to  be\nbuilt  with the functions even though the default is to use the macros - this allows applica‐\ntions to choose at app buildtime whether or not to use macros (previously impossible  because\nthe functions weren't in the default build.)\n\n\nXII. Changes to Libpng from version 1.5.x to 1.6.x\nA  \"simplified  API\"  has been added (see documentation in png.h and a simple example in con‐\ntrib/examples/pngtopng.c).  The new publicly visible API includes the following:\n\nmacros:\nPNGFORMAT*\nPNGIMAGE*\nstructures:\npngcontrol\npngimage\nread functions\npngimagebeginreadfromfile()\npngimagebeginreadfromstdio()\npngimagebeginreadfrommemory()\npngimagefinishread()\npngimagefree()\nwrite functions\npngimagewritetofile()\npngimagewritetomemory()\npngimagewritetostdio()\n\nStarting with libpng-1.6.0, you can configure libpng to prefix all  exported  symbols,  using\nthe PNGPREFIX macro.\n\nWe  no  longer include string.h in png.h.  The include statement has been moved to pngpriv.h,\nwhere it is not accessible by applications.  Applications that need access to information  in\nstring.h  must  add  an  '#include <string.h>' directive.  It does not matter whether this is\nplaced prior to or after the '#include \"png.h\"' directive.\n\nThe following API are now DEPRECATED:\npnginfoinit3()\npngconverttorfc1123() which has been replaced\nwith pngconverttorfc1123buffer()\npngmallocdefault()\npngfreedefault()\npngresetzstream()\n\nThe following have been removed:\npnggetiochunkname(), which has been replaced\nwith pnggetiochunktype().  The new\nfunction returns a 32-bit integer instead of\na string.\nThe pngsizeof(), pngstrlen(), pngmemcpy(), pngmemcmp(), and\npngmemset() macros are no longer used in the libpng sources and\nhave been removed.  These had already been made invisible to applications\n(i.e., defined in the private pngpriv.h header file) since libpng-1.5.0.\n\nThe signatures of many exported functions were changed, such that\npngstructp became pngstructrp or pngconststructrp\npnginfop became  pnginforp  or  pngconstinforp  where  \"rp\"  indicates  a  \"restricted\npointer\".\n\nDropped  support  for 16-bit platforms. The support for FAR/far types has been eliminated and\nthe definition of pngallocsizet is now controlled by a flag so that 'small sizet' systems\ncan select it if necessary.\n\nError detection in some chunks has improved; in particular the iCCP  chunk  reader  now  does\npretty  complete  validation of the basic format.  Some bad profiles that were previously ac‐\ncepted are now accepted with a warning or rejected,  depending  upon  the  pngsetbenigner‐\nrors()  setting,  in  particular  the  very  old  broken Microsoft/HP 3144-byte sRGB profile.\nStarting with libpng-1.6.11, recognizing and checking sRGB profiles can be avoided  by  means\nof\n\n#if defined(PNGSKIPsRGBCHECKPROFILE) &&         defined(PNGSETOPTIONSUPPORTED)\npngsetoption(pngptr, PNGSKIPsRGBCHECKPROFILE,\nPNGOPTIONON);\n#endif\n\nIt's not a good idea to do this if you are using the \"simplified API\", which needs to be able\nto recognize sRGB profiles conveyed via the iCCP chunk.\n\nThe  PNG spec requirement that only grayscale profiles may appear in images with color type 0\nor 4 and that even if the image only contains gray pixels, only RGB profiles  may  appear  in\nimages  with  color type 2, 3, or 6, is now enforced.  The sRGB chunk is allowed to appear in\nimages with any color type and is interpreted by libpng to  convey  a  one-tracer-curve  gray\nprofile or a three-tracer-curve RGB profile as appropriate.\n\nLibpng  1.5.x erroneously used /MD for Debug DLL builds; if you used the debug builds in your\napp and you changed your app to use /MD you will need to change it back to  /MDd  for  libpng\n1.6.x.\n\nPrior to libpng-1.6.0 a warning would be issued if the iTXt chunk contained an empty language\nfield or an empty translated keyword.  Both of these are allowed by the PNG specification, so\nthese warnings are no longer issued.\n\nThe library now issues an error if the application attempts to set a transform after it calls\npngreadupdateinfo()   or   if   it   attempts  to  call  both  pngreadupdateinfo()  and\npngstartreadimage() or to call either of them more than once.\n\nThe default condition for benignerrors is now to treat benign errors as warnings while read‐\ning and as errors while writing.\n\nThe library now issues a warning if both background processing and RGB to gray are used  when\ngamma  correction  happens.  As with previous versions of the library the results are numeri‐\ncally very incorrect in this case.\n\nThere are some minor arithmetic changes in some transforms such as pngsetbackground(), that\nmight be detected by certain regression tests.\n\nUnknown chunk handling has been improved internally, without any API change.  This adds  more\ncorrect  option  control  of the unknown handling, corrects a pre-existing bug where the per-\nchunk 'keep' setting is ignored, and makes it possible to skip IDAT chunks in the  sequential\nreader.\n\nThe  machine-generated  configure files are no longer included in branches libpng16 and later\nof the GIT repository.  They continue to be included in the tarball releases, however.\n\nLibpng-1.6.0 through 1.6.2 used the CMF bytes at the beginning of the IDAT stream to set  the\nsize  of  the sliding window for reading instead of using the default 32-kbyte sliding window\nsize.  It was discovered that there are hundreds of PNG files in the wild that have incorrect\nCMF bytes that caused zlib to issue the \"invalid distance too far back\" error and reject  the\nfile.  Libpng-1.6.3 and later calculate their own safe CMF from the image dimensions, provide\na  way  to  revert  to the libpng-1.5.x behavior (ignoring the CMF bytes and using a 32-kbyte\nsliding window), by using\n\npngsetoption(pngptr, PNGMAXIMUMINFLATEWINDOW,\nPNGOPTIONON);\n\nand provide a tool (contrib/tools/pngfix) for rewriting a PNG file while optimizing  the  CMF\nbytes in its IDAT chunk correctly.\n\nLibpng-1.6.0 and libpng-1.6.1 wrote uncompressed iTXt chunks with the wrong length, which re‐\nsulted  in  PNG files that cannot be read beyond the bad iTXt chunk.  This error was fixed in\nlibpng-1.6.3, and a tool (called contrib/tools/png-fix-itxt) has been  added  to  the  libpng\ndistribution.\n\nStarting  with  libpng-1.6.17,  the  PNGSAFELIMITS macro was eliminated and safe limits are\nused by default (users who need larger limits can still override them at compile time or  run\ntime, as described above).\n\nThe new limits are\ndefault   spec limit\npnguserwidthmax         1,000,000  2,147,483,647\npnguserheightmax        1,000,000  2,147,483,647\npnguserchunkcachemax         128  unlimited\npnguserchunkmallocmax  8,000,000  unlimited\n\nStarting  with  libpng-1.6.18,  a  PNGRELEASEBUILD  macro  was  added, which allows library\nbuilders to control compilation for an installed system (a release build).  It can be set for\ntesting debug or beta builds to ensure that they will compile when the build type is switched\nto RC or STABLE. In essence this overrides the PNGLIBPNGBUILDBASETYPE definition which is\nnot directly user controllable.\n\nStarting with libpng-1.6.19, attempting to set an over-length PLTE chunk is an error.  Previ‐\nously  this requirement of the PNG specification was not enforced, and the palette was always\nlimited to 256 entries. An over-length PLTE chunk found in an input  PNG  is  silently  trun‐\ncated.\n\nStarting  with  libpng-1.6.31, the eXIf chunk is supported. Libpng does not attempt to decode\nthe Exif profile; it simply returns a byte array containing the profile to the calling appli‐\ncation which must do its own decoding.\n\n\nXIII. Detecting libpng\nThe pnggetioptr() function has been present since libpng-0.88, has never changed,  and  is\nunaffected  by  conditional  compilation  macros.  It is the best choice for use in configure\nscripts for detecting the presence of any libpng version since 0.88.  In an autoconf \"config‐\nure.in\" you could use\n\nACCHECKLIB(png, pnggetioptr, ...)\n\n\nXV. Source code repository\nSince about February 2009, version 1.2.34, libpng has been under \"git\" source  control.   The\ngit  repository was built from old libpng-x.y.z.tar.gz files going back to version 0.70.  You\ncan access the git repository (read only) at\n\nhttps://github.com/pnggroup/libpng or\nhttps://git.code.sf.net/p/libpng/code.git\n\nor you can browse it with a web browser at\n\nhttps://github.com/pnggroup/libpng or\nhttps://sourceforge.net/p/libpng/code/ci/libpng16/tree/\n\nPatches can be sent to png-mng-implement at lists.sourceforge.net or uploaded to  the  libpng\nbug tracker at\n\nhttps://libpng.sourceforge.io/\n\nor as a \"pull request\" to\n\nhttps://github.com/pnggroup/libpng/pulls\n\nWe  also  accept  patches built from the tar or zip distributions, and simple verbal descrip‐\ntions of bug fixes, reported either to the SourceForge bug tracker, to the  png-mng-implement\nat lists.sf.net mailing list, as github issues.\n\n\nXV. Coding style\nOur  coding  style  is  similar  to the \"Allman\" style (See https://en.wikipedia.org/wiki/In‐\ndentstyle#Allmanstyle), with curly braces on separate lines:\n\nif (condition)\n{\naction;\n}\n\nelse if (another condition)\n{\nanother action;\n}\n\nThe braces can be omitted from simple one-line actions:\n\nif (condition)\nreturn 0;\n\nWe use 3-space indentation, except for continued statements which are  usually  indented  the\nsame as the first line of the statement plus four more spaces.\n\nFor macro definitions we use 2-space indentation, always leaving the \"#\" in the first column.\n\n#ifndef PNGNOFEATURE\n#  ifndef PNGFEATURESUPPORTED\n#    define PNGFEATURESUPPORTED\n#  endif\n#endif\n\nComments  appear  with the leading \"/*\" at the same indentation as the statement that follows\nthe comment:\n\n/* Single-line comment */\nstatement;\n\n/* This is a multiple-line\n* comment.\n*/\nstatement;\n\nVery short comments can be placed after the end of the statement to which they pertain:\n\nstatement;    /* comment */\n\nWe don't use C++ style (\"//\") comments. We have, however, used them in the past in some  now-\nabandoned MMX assembler code.\n\nFunctions and their curly braces are not indented, and exported functions are marked with PN‐\nGAPI:\n\n/* This is a public function that is visible to\n* application programmers. It does thus-and-so.\n*/\nvoid PNGAPI\npngexportedfunction(pngptr, pnginfo, foo)\n{\nbody;\n}\n\nThe  return type and decorations are placed on a separate line ahead of the function name, as\nillustrated above.\n\nThe prototypes for all exported functions appear in png.h, above the comment that says\n\n/* Maintainer: Put new public prototypes here ... */\n\nWe mark all non-exported functions with \"/* PRIVATE */\"\":\n\nvoid /* PRIVATE */\npngnonexportedfunction(pngptr, pnginfo, foo)\n{\nbody;\n}\n\nThe prototypes for non-exported functions (except for those in pngtest) appear  in  pngpriv.h\nabove the comment that says\n\n/* Maintainer: Put new private prototypes here ^ */\n\nTo  avoid  polluting  the global namespace, the names of all exported functions and variables\nbegin with \"png\", and all publicly visible C preprocessor macros begin with \"PNG\".   We  re‐\nquest  that  applications that use libpng *not* begin any of their own symbols with either of\nthese strings.\n\nWe put a space after the \"sizeof\" operator and we omit the optional  parentheses  around  its\nargument  when  the  argument  is  an  expression, not a type name, and we always enclose the\nsizeof operator, with its argument, in parentheses:\n\n(sizeof (pnguint32))\n(sizeof array)\n\nPrior to libpng-1.6.0 we used a \"pngsizeof()\" macro, formatted as though it were a function.\n\nControl keywords if, for, while, and switch are always followed by  a  space  to  distinguish\nthem from function calls, which have no trailing space.\n\nWe  put  a  space  after  each comma and after each semicolon in \"for\" statements, and we put\nspaces before and after each C binary operator and after \"for\" or \"while\",  and  before  \"?\".\nWe  don't put a space between a typecast and the expression being cast, nor do we put one be‐\ntween a function name and the left parenthesis that follows it:\n\nfor (i = 2; i > 0; --i)\ny[i] = a(x) + (int)b;\n\nWe prefer #ifdef and #ifndef to #if defined() and #if !defined() when there is only one macro\nbeing tested.  We always use parentheses with \"defined\".\n\nWe express integer constants that are used as bit masks in hex format, with an even number of\nlower-case hex digits, and to make them unsigned (e.g., 0x00U, 0xffU, 0x0100U)  and  long  if\nthey are greater than 0x7fff (e.g., 0xffffUL).\n\nWe prefer to use underscores rather than camelCase in names, except for a few type names that\nwe inherit from zlib.h.\n\nWe  prefer  \"if  (something  !=  0)\"  and  \"if (something == 0)\" over \"if (something)\" and if\n\"(!something)\", respectively, and for pointers we prefer \"if (somepointer != NULL)\"  or  \"if\n(somepointer == NULL)\".\n\nWe do not use the TAB character for indentation in the C sources.\n\nLines do not exceed 80 characters.\n\nOther rules can be inferred by inspecting the libpng source.\n\n"
                }
            ]
        },
        "NOTE": {
            "content": "Note about libpng version numbers:\n\nDue  to  various  miscommunications, unforeseen code incompatibilities and occasional factors\noutside the authors' control, version numbering on the library has not always been consistent\nand straightforward.  The following table summarizes matters since version 0.89c,  which  was\nthe first widely used release:\n\nsource               png.h    png.h  shared-lib\nversion              string   int    version\n-------              ------   -----  ----------\n0.89c \"1.0 beta 3\"     0.89      89  1.0.89\n0.90  \"1.0 beta 4\"     0.90      90  0.90  [should have been 2.0.90]\n0.95  \"1.0 beta 5\"     0.95      95  0.95  [should have been 2.0.95]\n0.96  \"1.0 beta 6\"     0.96      96  0.96  [should have been 2.0.96]\n0.97b \"1.00.97 beta 7\" 1.00.97   97  1.0.1 [should have been 2.0.97]\n0.97c                  0.97      97  2.0.97\n0.98                   0.98      98  2.0.98\n0.99                   0.99      98  2.0.99\n0.99a-m                0.99      99  2.0.99\n1.00                   1.00     100  2.1.0 [100 should be 10000]\n1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]\n1.0.1       png.h string is   10001  2.1.0\n1.0.1a-e    identical to the  10002  from here on, the shared library\n1.0.2       source version)   10002  is 2.V where V is the source code\n1.0.2a-b                      10003  version, except as noted.\n1.0.3                         10003\n1.0.3a-d                      10004\n1.0.4                         10004\n1.0.4a-f                      10005\n1.0.5 (+ 2 patches)           10005\n1.0.5a-d                      10006\n1.0.5e-r                      10100 (not source compatible)\n1.0.5s-v                      10006 (not binary compatible)\n1.0.6 (+ 3 patches)           10006 (still binary incompatible)\n1.0.6d-f                      10007 (still binary incompatible)\n1.0.6g                        10007\n1.0.6h                        10007  10.6h (testing xy.z so-numbering)\n1.0.6i                        10007  10.6i\n1.0.6j                        10007  2.1.0.6j (incompatible with 1.0.0)\n1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compatible)\n1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compatible)\n1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)\n1.0.7                    1    10007  (still compatible)\n...\n1.0.69                  10    10069  10.so.0.69[.0]\n...\n1.2.59                  13    10259  12.so.0.59[.0]\n...\n1.4.20                  14    10420  14.so.0.20[.0]\n...\n1.5.30                  15    10530  15.so.15.30[.0]\n...\n1.6.35                  16    10635  16.so.16.35[.0]\n\nHenceforth  the  source  version  will  match the shared-library minor and patch numbers; the\nshared-library major version number will be used for changes in backward compatibility, as it\nis intended.  The PNGPNGLIBVER macro, which is not used within libpng but is available  for\napplications,  is  an  unsigned integer of the form XYYZZ corresponding to the source version\nX.Y.Z (leading zeros in Y and Z).  Beta versions were given the previous public release  num‐\nber plus a letter, until version 1.0.6j; from then on they were given the upcoming public re‐\nlease number plus \"betaNN\" or \"rcNN\".\n\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "png(5)\n\nThe PNG (Portable Network Graphics) format specification.\n",
            "subsections": [
                {
                    "name": "libpng",
                    "content": "http://www.libpng.org/pub/png/libpng.html (canonical home page)\nhttps://github.com/pnggroup/libpng (canonical Git repository)\nhttps://libpng.sourceforge.io (downloadable archives)\n"
                },
                {
                    "name": "zlib",
                    "content": "https://zlib.net (canonical home page)\nhttps://github.com/madler/zlib (canonical Git repository)\nA copy of zlib may also be found at the same location as libpng.\n\nIn the case of any inconsistency between the PNG specification and this library, the specifi‐\ncation takes precedence.\n\n"
                }
            ]
        },
        "AUTHORS": {
            "content": "This man page: Initially created by Glenn Randers-Pehrson.  Maintained by Cosmin Truta.\n\nThe  contributing  authors  would like to thank all those who helped with testing, bug fixes,\nand patience.  This wouldn't have been possible without all of you.\n\nThanks to Frank J. T. Wojcik for helping with the documentation.\n\nLibpng: Initially created in 1995 by Guy Eric Schalnat, then of Group 42, Inc.  Maintained by\nCosmin Truta.\n\nSupported by the PNG development group.\npng-mng-implement   at    lists.sourceforge.net.    (Subscription    is    required;    visit\nhttps://lists.sourceforge.net/lists/listinfo/png-mng-implement to subscribe.)\n\n\nFebruary 23, 2024                                LIBPNG(3)",
            "subsections": []
        }
    },
    "summary": "libpng - Portable Network Graphics (PNG) Reference Library 1.6.43",
    "flags": [],
    "examples": [],
    "see_also": [
        {
            "name": "png",
            "section": "5",
            "url": "https://www.chedong.com/phpMan.php/man/png/5/json"
        }
    ]
}