colors

extract colors from pictures
git clone git://git.2f30.org/colors
Log | Files | Refs | README | LICENSE

png.c (1344B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <err.h>
      3 #include <stdio.h>
      4 
      5 #include <png.h>
      6 #include "colors.h"
      7 
      8 void
      9 parseimg_png(FILE *fp, void (*fn)(int, int, int))
     10 {
     11 	png_structp png_struct_p;
     12 	png_infop png_info_p;
     13 	png_bytepp png_row_p;
     14 	png_uint_32 y, x, width, height;
     15 	int depth, color, interlace;
     16 
     17 	png_struct_p = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
     18 	png_info_p = png_create_info_struct(png_struct_p);
     19 	if (!png_struct_p || !png_info_p || setjmp(png_jmpbuf(png_struct_p)))
     20 		errx(1, "failed to initialize libpng");
     21 
     22 	png_init_io(png_struct_p, fp);
     23 	png_set_add_alpha(png_struct_p, 255, PNG_FILLER_AFTER);
     24 	png_set_gray_to_rgb(png_struct_p);
     25 	png_read_png(png_struct_p, png_info_p, PNG_TRANSFORM_STRIP_16 |
     26 	             PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, NULL);
     27 	png_get_IHDR(png_struct_p, png_info_p, &width, &height, &depth,
     28 	             &color, &interlace, NULL, NULL);
     29 	png_row_p = png_get_rows(png_struct_p, png_info_p);
     30 
     31 	for (y = 0; y < height; y++) {
     32 		png_byte *row = png_row_p[y];
     33 		for (x = 0; x < width; x++) {
     34 			png_byte *p = &row[x * 4];
     35 			if (color == PNG_COLOR_TYPE_RGB_ALPHA && !p[3])
     36 				continue;
     37 			fn(p[0], p[1], p[2]);
     38 		}
     39 	}
     40 
     41 	png_free_data(png_struct_p, png_info_p, PNG_FREE_ALL, -1);
     42 	png_destroy_read_struct(&png_struct_p, &png_info_p, NULL);
     43 }