fukasawa e60969
/*- pngpixel
fukasawa e60969
 *
fukasawa e60969
 * COPYRIGHT: Written by John Cunningham Bowler, 2011.
fukasawa e60969
 * To the extent possible under law, the author has waived all copyright and
fukasawa e60969
 * related or neighboring rights to this work.  This work is published from:
fukasawa e60969
 * United States.
fukasawa e60969
 *
fukasawa e60969
 * Read a single pixel value from a PNG file.
fukasawa e60969
 *
fukasawa e60969
 * This code illustrates basic 'by-row' reading of a PNG file using libpng.
fukasawa e60969
 * Rows are read until a particular pixel is found; the value of this pixel is
fukasawa e60969
 * then printed on stdout.
fukasawa e60969
 *
fukasawa e60969
 * The code illustrates how to do this on interlaced as well as non-interlaced
fukasawa e60969
 * images.  Normally you would call png_set_interlace_handling() to have libpng
fukasawa e60969
 * deal with the interlace for you, but that obliges you to buffer half of the
fukasawa e60969
 * image to assemble the interlaced rows.  In this code
fukasawa e60969
 * png_set_interlace_handling() is not called and, instead, the code handles the
fukasawa e60969
 * interlace passes directly looking for the required pixel.
fukasawa e60969
 */
fukasawa e60969
#include <stdlib.h></stdlib.h>
fukasawa e60969
#include <stdio.h></stdio.h>
fukasawa e60969
#include <setjmp.h> /* required for error handling */</setjmp.h>
fukasawa e60969
fukasawa e60969
/* Normally use <png.h> here to get the installed libpng, but this is done to</png.h>
fukasawa e60969
 * ensure the code picks up the local libpng implementation:
fukasawa e60969
 */
fukasawa e60969
#include "../../png.h"
fukasawa e60969
fukasawa e60969
#if defined(PNG_READ_SUPPORTED) && defined(PNG_SEQUENTIAL_READ_SUPPORTED)
fukasawa e60969
fukasawa e60969
/* Return component 'c' of pixel 'x' from the given row. */
fukasawa e60969
static unsigned int
fukasawa e60969
component(png_const_bytep row, png_uint_32 x, unsigned int c,
fukasawa e60969
   unsigned int bit_depth, unsigned int channels)
fukasawa e60969
{
fukasawa e60969
   /* PNG images can be up to 2^31 pixels wide, but this means they can be up to
fukasawa e60969
    * 2^37 bits wide (for a 64-bit pixel - the largest possible) and hence 2^34
fukasawa e60969
    * bytes wide.  Since the row fitted into memory, however, the following must
fukasawa e60969
    * work:
fukasawa e60969
    */
fukasawa e60969
   png_uint_32 bit_offset_hi = bit_depth * ((x >> 6) * channels);
fukasawa e60969
   png_uint_32 bit_offset_lo = bit_depth * ((x & 0x3f) * channels + c);
fukasawa e60969
fukasawa e60969
   row = (png_const_bytep)(((PNG_CONST png_byte (*)[8])row) + bit_offset_hi);
fukasawa e60969
   row += bit_offset_lo >> 3;
fukasawa e60969
   bit_offset_lo &= 0x07;
fukasawa e60969
fukasawa e60969
   /* PNG pixels are packed into bytes to put the first pixel in the highest
fukasawa e60969
    * bits of the byte and into two bytes for 16-bit values with the high 8 bits
fukasawa e60969
    * first, so:
fukasawa e60969
    */
fukasawa e60969
   switch (bit_depth)
fukasawa e60969
   {
fukasawa e60969
      case 1: return (row[0] >> (7-bit_offset_lo)) & 0x01;
fukasawa e60969
      case 2: return (row[0] >> (6-bit_offset_lo)) & 0x03;
fukasawa e60969
      case 4: return (row[0] >> (4-bit_offset_lo)) & 0x0f;
fukasawa e60969
      case 8: return row[0];
fukasawa e60969
      case 16: return (row[0] << 8) + row[1];
fukasawa e60969
      default:
fukasawa e60969
         /* This should never happen; it indicates a bug in this program or in
fukasawa e60969
          * libpng itself:
fukasawa e60969
          */
fukasawa e60969
         fprintf(stderr, "pngpixel: invalid bit depth %u\n", bit_depth);
fukasawa e60969
         exit(1);
fukasawa e60969
   }
fukasawa e60969
}
fukasawa e60969
fukasawa e60969
/* Print a pixel from a row returned by libpng; determine the row format, find
fukasawa e60969
 * the pixel, and print the relevant information to stdout.
fukasawa e60969
 */
fukasawa e60969
static void
fukasawa e60969
print_pixel(png_structp png_ptr, png_infop info_ptr, png_const_bytep row,
fukasawa e60969
   png_uint_32 x)
fukasawa e60969
{
fukasawa e60969
   PNG_CONST unsigned int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
fukasawa e60969
fukasawa e60969
   switch (png_get_color_type(png_ptr, info_ptr))
fukasawa e60969
   {
fukasawa e60969
      case PNG_COLOR_TYPE_GRAY:
fukasawa e60969
         printf("GRAY %u\n", component(row, x, 0, bit_depth, 1));
fukasawa e60969
         return;
fukasawa e60969
fukasawa e60969
      /* The palette case is slightly more difficult - the palette and, if
fukasawa e60969
       * present, the tRNS ('transparency', though the values are really
fukasawa e60969
       * opacity) data must be read to give the full picture:
fukasawa e60969
       */
fukasawa e60969
      case PNG_COLOR_TYPE_PALETTE:
fukasawa e60969
         {
fukasawa e60969
            PNG_CONST int index = component(row, x, 0, bit_depth, 1);
fukasawa e60969
            png_colorp palette = NULL;
fukasawa e60969
            int num_palette = 0;
fukasawa e60969
fukasawa e60969
            if ((png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette) &
fukasawa e60969
               PNG_INFO_PLTE) && num_palette > 0 && palette != NULL)
fukasawa e60969
            {
fukasawa e60969
               png_bytep trans_alpha = NULL;
fukasawa e60969
               int num_trans = 0;
fukasawa e60969
               if ((png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans,
fukasawa e60969
                  NULL) & PNG_INFO_tRNS) && num_trans > 0 &&
fukasawa e60969
                  trans_alpha != NULL)
fukasawa e60969
                  printf("INDEXED %u = %d %d %d %d\n", index,
fukasawa e60969
                     palette[index].red, palette[index].green,
fukasawa e60969
                     palette[index].blue,
fukasawa e60969
                     index < num_trans ? trans_alpha[index] : 255);
fukasawa e60969
fukasawa e60969
               else /* no transparency */
fukasawa e60969
                  printf("INDEXED %u = %d %d %d\n", index,
fukasawa e60969
                     palette[index].red, palette[index].green,
fukasawa e60969
                     palette[index].blue);
fukasawa e60969
            }
fukasawa e60969
fukasawa e60969
            else
fukasawa e60969
               printf("INDEXED %u = invalid index\n", index);
fukasawa e60969
         }
fukasawa e60969
         return;
fukasawa e60969
fukasawa e60969
      case PNG_COLOR_TYPE_RGB:
fukasawa e60969
         printf("RGB %u %u %u\n", component(row, x, 0, bit_depth, 3),
fukasawa e60969
            component(row, x, 1, bit_depth, 3),
fukasawa e60969
            component(row, x, 2, bit_depth, 3));
fukasawa e60969
         return;
fukasawa e60969
fukasawa e60969
      case PNG_COLOR_TYPE_GRAY_ALPHA:
fukasawa e60969
         printf("GRAY+ALPHA %u %u\n", component(row, x, 0, bit_depth, 2),
fukasawa e60969
            component(row, x, 1, bit_depth, 2));
fukasawa e60969
         return;
fukasawa e60969
fukasawa e60969
      case PNG_COLOR_TYPE_RGB_ALPHA:
fukasawa e60969
         printf("RGBA %u %u %u %u\n", component(row, x, 0, bit_depth, 4),
fukasawa e60969
            component(row, x, 1, bit_depth, 4),
fukasawa e60969
            component(row, x, 2, bit_depth, 4),
fukasawa e60969
            component(row, x, 3, bit_depth, 4));
fukasawa e60969
         return;
fukasawa e60969
fukasawa e60969
      default:
fukasawa e60969
         png_error(png_ptr, "pngpixel: invalid color type");
fukasawa e60969
   }
fukasawa e60969
}
fukasawa e60969
fukasawa e60969
int main(int argc, const char **argv)
fukasawa e60969
{
fukasawa e60969
   /* This program uses the default, <setjmp.h> based, libpng error handling</setjmp.h>
fukasawa e60969
    * mechanism, therefore any local variable that exists before the call to
fukasawa e60969
    * setjmp and is changed after the call to setjmp returns successfully must
fukasawa e60969
    * be declared with 'volatile' to ensure that their values don't get
fukasawa e60969
    * destroyed by longjmp:
fukasawa e60969
    */
fukasawa e60969
   volatile int result = 1/*fail*/;
fukasawa e60969
fukasawa e60969
   if (argc == 4)
fukasawa e60969
   {
fukasawa e60969
      long x = atol(argv[1]);
fukasawa e60969
      long y = atol(argv[2]);
fukasawa e60969
      FILE *f = fopen(argv[3], "rb");
fukasawa e60969
      volatile png_bytep row = NULL;
fukasawa e60969
fukasawa e60969
      if (f != NULL)
fukasawa e60969
      {
fukasawa e60969
         /* libpng requires a callback function for handling errors; this
fukasawa e60969
          * callback must not return.  The default callback function uses a
fukasawa e60969
          * stored <setjmp.h> style jmp_buf which is held in a png_struct and</setjmp.h>
fukasawa e60969
          * writes error messages to stderr.  Creating the png_struct is a
fukasawa e60969
          * little tricky; just copy the following code.
fukasawa e60969
          */
fukasawa e60969
         png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
fukasawa e60969
            NULL, NULL, NULL);
fukasawa e60969
fukasawa e60969
         if (png_ptr != NULL)
fukasawa e60969
         {
fukasawa e60969
            png_infop info_ptr = png_create_info_struct(png_ptr);
fukasawa e60969
fukasawa e60969
            if (info_ptr != NULL)
fukasawa e60969
            {
fukasawa e60969
               /* Declare stack variables to hold pointers to locally allocated
fukasawa e60969
                * data.
fukasawa e60969
                */
fukasawa e60969
fukasawa e60969
               /* Initialize the error control buffer: */
fukasawa e60969
               if (setjmp(png_jmpbuf(png_ptr)) == 0)
fukasawa e60969
               {
fukasawa e60969
                  png_uint_32 width, height;
fukasawa e60969
                  int bit_depth, color_type, interlace_method,
fukasawa e60969
                     compression_method, filter_method;
fukasawa e60969
                  png_bytep row_tmp;
fukasawa e60969
fukasawa e60969
                  /* Now associate the recently opened (FILE*) with the default
fukasawa e60969
                   * libpng initialization functions.  Sometimes libpng is
fukasawa e60969
                   * compiled without stdio support (it can be difficult to do
fukasawa e60969
                   * in some environments); in that case you will have to write
fukasawa e60969
                   * your own read callback to read data from the (FILE*).
fukasawa e60969
                   */
fukasawa e60969
                  png_init_io(png_ptr, f);
fukasawa e60969
fukasawa e60969
                  /* And read the first part of the PNG file - the header and
fukasawa e60969
                   * all the information up to the first pixel.
fukasawa e60969
                   */
fukasawa e60969
                  png_read_info(png_ptr, info_ptr);
fukasawa e60969
fukasawa e60969
                  /* This fills in enough information to tell us the width of
fukasawa e60969
                   * each row in bytes, allocate the appropriate amount of
fukasawa e60969
                   * space.  In this case png_malloc is used - it will not
fukasawa e60969
                   * return if memory isn't available.
fukasawa e60969
                   */
fukasawa e60969
                  row = png_malloc(png_ptr, png_get_rowbytes(png_ptr,
fukasawa e60969
                     info_ptr));
fukasawa e60969
fukasawa e60969
                  /* To avoid the overhead of using a volatile auto copy row_tmp
fukasawa e60969
                   * to a local here - just use row for the png_free below.
fukasawa e60969
                   */
fukasawa e60969
                  row_tmp = row;
fukasawa e60969
fukasawa e60969
                  /* All the information we need is in the header is returned by
fukasawa e60969
                   * png_get_IHDR, if this fails we can now use 'png_error' to
fukasawa e60969
                   * signal the error and return control to the setjmp above.
fukasawa e60969
                   */
fukasawa e60969
                  if (png_get_IHDR(png_ptr, info_ptr, &width, &height,
fukasawa e60969
                     &bit_depth, &color_type, &interlace_method,
fukasawa e60969
                     &compression_method, &filter_method))
fukasawa e60969
                  {
fukasawa e60969
                     int passes, pass;
fukasawa e60969
fukasawa e60969
                     /* png_set_interlace_handling returns the number of
fukasawa e60969
                      * passes required as well as turning on libpng's
fukasawa e60969
                      * handling, but since we do it ourselves this is
fukasawa e60969
                      * necessary:
fukasawa e60969
                      */
fukasawa e60969
                     switch (interlace_method)
fukasawa e60969
                     {
fukasawa e60969
                        case PNG_INTERLACE_NONE:
fukasawa e60969
                           passes = 1;
fukasawa e60969
                           break;
fukasawa e60969
fukasawa e60969
                        case PNG_INTERLACE_ADAM7:
fukasawa e60969
                           passes = PNG_INTERLACE_ADAM7_PASSES;
fukasawa e60969
                           break;
fukasawa e60969
fukasawa e60969
                        default:
fukasawa e60969
                           png_error(png_ptr, "pngpixel: unknown interlace");
fukasawa e60969
                     }
fukasawa e60969
fukasawa e60969
                     /* Now read the pixels, pass-by-pass, row-by-row: */
fukasawa e60969
                     png_start_read_image(png_ptr);
fukasawa e60969
fukasawa e60969
                     for (pass=0; pass
fukasawa e60969
                     {
fukasawa e60969
                        png_uint_32 ystart, xstart, ystep, xstep;
fukasawa e60969
                        png_uint_32 py;
fukasawa e60969
fukasawa e60969
                        if (interlace_method == PNG_INTERLACE_ADAM7)
fukasawa e60969
                        {
fukasawa e60969
                           /* Sometimes the whole pass is empty because the
fukasawa e60969
                            * image is too narrow or too short.  libpng
fukasawa e60969
                            * expects to be called for each row that is
fukasawa e60969
                            * present in the pass, so it may be necessary to
fukasawa e60969
                            * skip the loop below (over py) if the image is
fukasawa e60969
                            * too narrow.
fukasawa e60969
                            */
fukasawa e60969
                           if (PNG_PASS_COLS(width, pass) == 0)
fukasawa e60969
                              continue;
fukasawa e60969
fukasawa e60969
                           /* We need the starting pixel and the offset
fukasawa e60969
                            * between each pixel in this pass; use the macros
fukasawa e60969
                            * in png.h:
fukasawa e60969
                            */
fukasawa e60969
                           xstart = PNG_PASS_START_COL(pass);
fukasawa e60969
                           ystart = PNG_PASS_START_ROW(pass);
fukasawa e60969
                           xstep = PNG_PASS_COL_OFFSET(pass);
fukasawa e60969
                           ystep = PNG_PASS_ROW_OFFSET(pass);
fukasawa e60969
                        }
fukasawa e60969
fukasawa e60969
                        else
fukasawa e60969
                        {
fukasawa e60969
                           ystart = xstart = 0;
fukasawa e60969
                           ystep = xstep = 1;
fukasawa e60969
                        }
fukasawa e60969
fukasawa e60969
                        /* To find the pixel, loop over 'py' for each pass
fukasawa e60969
                         * reading a row and then checking to see if it
fukasawa e60969
                         * contains the pixel.
fukasawa e60969
                         */
fukasawa e60969
                        for (py = ystart; py < height; py += ystep)
fukasawa e60969
                        {
fukasawa e60969
                           png_uint_32 px, ppx;
fukasawa e60969
fukasawa e60969
                           /* png_read_row takes two pointers.  When libpng
fukasawa e60969
                            * handles the interlace the first is filled in
fukasawa e60969
                            * pixel-by-pixel, and the second receives the same
fukasawa e60969
                            * pixels but they are replicated across the
fukasawa e60969
                            * unwritten pixels so far for each pass.  When we
fukasawa e60969
                            * do the interlace, however, they just contain
fukasawa e60969
                            * the pixels from the interlace pass - giving
fukasawa e60969
                            * both is wasteful and pointless, so we pass a
fukasawa e60969
                            * NULL pointer.
fukasawa e60969
                            */
fukasawa e60969
                           png_read_row(png_ptr, row_tmp, NULL);
fukasawa e60969
fukasawa e60969
                           /* Now find the pixel if it is in this row; there
fukasawa e60969
                            * are, of course, much better ways of doing this
fukasawa e60969
                            * than using a for loop:
fukasawa e60969
                            */
fukasawa e60969
                           if (y == py) for (px = xstart, ppx = 0;
fukasawa e60969
                              px < width; px += xstep, ++ppx) if (x == px)
fukasawa e60969
                           {
fukasawa e60969
                              /* 'ppx' is the index of the pixel in the row
fukasawa e60969
                               * buffer.
fukasawa e60969
                               */
fukasawa e60969
                              print_pixel(png_ptr, info_ptr, row_tmp, ppx);
fukasawa e60969
fukasawa e60969
                              /* Now terminate the loops early - we have
fukasawa e60969
                               * found and handled the required data.
fukasawa e60969
                               */
fukasawa e60969
                              goto pass_loop_end;
fukasawa e60969
                           } /* x loop */
fukasawa e60969
                        } /* y loop */
fukasawa e60969
                     } /* pass loop */
fukasawa e60969
fukasawa e60969
                     /* Finally free the temporary buffer: */
fukasawa e60969
                  pass_loop_end:
fukasawa e60969
                     row = NULL;
fukasawa e60969
                     png_free(png_ptr, row_tmp);
fukasawa e60969
                  }
fukasawa e60969
fukasawa e60969
                  else
fukasawa e60969
                     png_error(png_ptr, "pngpixel: png_get_IHDR failed");
fukasawa e60969
fukasawa e60969
               }
fukasawa e60969
fukasawa e60969
               else
fukasawa e60969
               {
fukasawa e60969
                  /* Else libpng has raised an error.  An error message has
fukasawa e60969
                   * already been output, so it is only necessary to clean up
fukasawa e60969
                   * locally allocated data:
fukasawa e60969
                   */
fukasawa e60969
                  if (row != NULL)
fukasawa e60969
                  {
fukasawa e60969
                     /* The default implementation of png_free never errors out
fukasawa e60969
                      * (it just crashes if something goes wrong), but the safe
fukasawa e60969
                      * way of using it is still to clear 'row' before calling
fukasawa e60969
                      * png_free:
fukasawa e60969
                      */
fukasawa e60969
                     png_bytep row_tmp = row;
fukasawa e60969
                     row = NULL;
fukasawa e60969
                     png_free(png_ptr, row_tmp);
fukasawa e60969
                  }
fukasawa e60969
               }
fukasawa e60969
fukasawa e60969
               png_destroy_info_struct(png_ptr, &info_ptr);
fukasawa e60969
            }
fukasawa e60969
fukasawa e60969
            else
fukasawa e60969
               fprintf(stderr, "pngpixel: out of memory allocating png_info\n");
fukasawa e60969
fukasawa e60969
            png_destroy_read_struct(&png_ptr, NULL, NULL);
fukasawa e60969
         }
fukasawa e60969
fukasawa e60969
         else
fukasawa e60969
            fprintf(stderr, "pngpixel: out of memory allocating png_struct\n");
fukasawa e60969
      }
fukasawa e60969
fukasawa e60969
      else
fukasawa e60969
         fprintf(stderr, "pngpixel: %s: could not open file\n", argv[3]);
fukasawa e60969
   }
fukasawa e60969
fukasawa e60969
   else
fukasawa e60969
      /* Wrong number of arguments */
fukasawa e60969
      fprintf(stderr, "pngpixel: usage: pngpixel x y png-file\n");
fukasawa e60969
fukasawa e60969
   return result;
fukasawa e60969
}
fukasawa e60969
#endif /* READ && SEQUENTIAL_READ */