libpng's man page makes a crap tutorial

tung's picture

If there were a competition for world's worst man page, libpng's would be right up there. Instead of individual man pages for each function and struct, it rolls everything into the one huge document. That would be acceptable if it gave descriptions for each of the functions, but it doesn't, instead providing an nigh-impenetrable wall of text which is borderline useless as a guide or a reference.

Misgivings aside, I've managed to extract the useful information for the simple loading of a PNG image and put it in the code sample below:

#include <png.h>
 
FILE *fp = fopen("image.png", "rb");
 
/* Optional: Make sure it's a PNG. */
char header[8];
fread(header, 1, 8, fp);
if (png_sig_cmp(header, 0, 8) != 0) {
    return (BLARG_IM_DED);
}
 
/* Those NULLs are: error_ptr, error_fn and warn_fn. */
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
 
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
    png_destroy_read_struct(&png_ptr, NULL, NULL);
    return (BLARG_IM_DED);
}
 
/* libpng's exception-style error handling using setjmp/longjmp.
   Return here in the event of an error.
   No special headers needed. */
if (setjmp(png_jmpbuf(png_ptr))) {
    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
    if (fp) {
        fclose(fp);
    }
    return (BLARG_IM_DED);
}
 
png_init_io(png_ptr, fp);
 
/* Skip this if you didn't check the header earlier. */
png_set_sig_bytes(png_ptr, 8);
 
/* No, this really doesn't return anything. */
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
 
fclose(fp);
fp = NULL;
 
/* Getting basic image info. */
int width = png_get_image_width(png_ptr, info_ptr);
int height = png_get_image_height(png_ptr, info_ptr);
 
/* Get IMAGE DATA. Comes in the form of an array of pointers to pixel rows. */
png_bytep *row_pointers = png_get_rows(png_ptr, info_ptr);
 
png_destroy_read_struct(&png_ptr, &info_ptr);

If you're just getting started, this should help more than reading the man page, or example.c, or png.h.