colors

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

commit ba0d3294c08b43fea5a4571aebc089ff6eef48bd
parent 6b73dd60c1bf9ce6dc80a3a423d24a74de4c922e
Author: sin <sin@2f30.org>
Date:   Fri,  5 Jun 2015 13:44:48 +0100

Simplify png parser

Diffstat:
Mpng.c | 61++++++++++++++++++++-----------------------------------------
1 file changed, 20 insertions(+), 41 deletions(-)

diff --git a/png.c b/png.c @@ -1,7 +1,6 @@ /* See LICENSE file for copyright and license details. */ #include <err.h> #include <stdio.h> -#include <stdlib.h> #include <png.h> #include "colors.h" @@ -9,61 +8,41 @@ void parseimg(char *f, void (*fn)(int, int, int)) { + png_structp png_struct_p; + png_infop png_info_p; + png_bytepp png_row_p; + png_uint_32 width, height; + int depth, color, interlace; + int y, x; FILE *fp; - png_structp png_ptr; - png_infop info_ptr; - png_byte hdr[8]; - png_bytep *rows; - int width, height; - int x, y; if (!(fp = fopen(f, "r"))) err(1, "fopen %s", f); - fread(hdr, 1, 8, fp); - if (png_sig_cmp(hdr, 0, 8)) - errx(1, "not a png file"); - png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); - info_ptr = png_create_info_struct(png_ptr); - if (!png_ptr || !info_ptr || setjmp(png_jmpbuf(png_ptr))) + png_struct_p = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + png_info_p = png_create_info_struct(png_struct_p); + if (!png_struct_p || !png_info_p || setjmp(png_jmpbuf(png_struct_p))) errx(1, "failed to initialize libpng"); - png_init_io(png_ptr, fp); - png_set_add_alpha(png_ptr, 255, PNG_FILLER_AFTER); - png_set_gray_to_rgb(png_ptr); - png_set_sig_bytes(png_ptr, 8); - png_read_info(png_ptr, info_ptr); + png_init_io(png_struct_p, fp); + png_set_add_alpha(png_struct_p, 255, PNG_FILLER_AFTER); + png_set_gray_to_rgb(png_struct_p); + png_read_png(png_struct_p, png_info_p, PNG_TRANSFORM_STRIP_16 | + PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND , NULL); + png_get_IHDR(png_struct_p, png_info_p, &width, &height, &depth, + &color, &interlace, NULL, NULL); + png_row_p = png_get_rows(png_struct_p, png_info_p); - width = png_get_image_width(png_ptr, info_ptr); - height = png_get_image_height(png_ptr, info_ptr); - png_read_update_info(png_ptr, info_ptr); - - if (setjmp(png_jmpbuf(png_ptr))) - errx(1, "failed to read image"); - - rows = malloc(sizeof(*rows) * height); - if (!rows) - err(1, "malloc"); for (y = 0; y < height; y++) { - rows[y] = malloc(png_get_rowbytes(png_ptr, info_ptr)); - if (!rows[y]) - err(1, "malloc"); - } - - png_read_image(png_ptr, rows); - - for (y = 0; y < height; y++) { - png_byte *row = rows[y]; + png_byte *row = png_row_p[y]; for (x = 0; x < width; x++) { png_byte *p = &row[x * 4]; fn(p[0], p[1], p[2]); } } - for (y = 0; y < height; y++) - free(rows[y]); - free(rows); + png_free_data(png_struct_p, png_info_p, PNG_FREE_ALL, -1); + png_destroy_read_struct(&png_struct_p, &png_info_p, NULL); fclose(fp); - }