| | 1 | #include <stdlib.h> |
| | 2 | #include <libpng/png.h> |
| | 3 | |
| | 4 | unsigned char *png_get_image_data(FILE *infile, int *image_width, int *image_height) |
| | 5 | { |
| | 6 | unsigned char buf[8]; |
| | 7 | |
| | 8 | fread(buf, 1, 8, infile); |
| | 9 | |
| | 10 | if(!png_sig_cmp(buf, 0, 8)) |
| | 11 | { |
| | 12 | png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); |
| | 13 | |
| | 14 | if (png_ptr) |
| | 15 | { |
| | 16 | png_infop info_ptr = png_create_info_struct(png_ptr); |
| | 17 | |
| | 18 | if (info_ptr) |
| | 19 | { |
| | 20 | if (setjmp(png_jmpbuf(png_ptr))) |
| | 21 | { |
| | 22 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL); |
| | 23 | return NULL; |
| | 24 | } |
| | 25 | |
| | 26 | png_init_io(png_ptr, infile); |
| | 27 | png_set_sig_bytes(png_ptr, 8); |
| | 28 | png_read_info(png_ptr, info_ptr); |
| | 29 | |
| | 30 | *image_height = png_get_image_height(png_ptr, info_ptr); |
| | 31 | *image_width = png_get_image_width(png_ptr, info_ptr); |
| | 32 | |
| | 33 | if (16 == png_get_bit_depth(png_ptr, info_ptr)) |
| | 34 | { |
| | 35 | png_set_strip_16(png_ptr); |
| | 36 | png_read_update_info(png_ptr, info_ptr); |
| | 37 | } |
| | 38 | |
| | 39 | png_uint_32 rowbytes = png_get_rowbytes(png_ptr, info_ptr); |
| | 40 | |
| | 41 | unsigned char *image_data = malloc(*image_height * rowbytes); |
| | 42 | |
| | 43 | if (NULL != image_data) |
| | 44 | { |
| | 45 | png_bytepp row_pointers = malloc(*image_height * sizeof(png_bytep)); |
| | 46 | |
| | 47 | if (NULL != row_pointers) |
| | 48 | { |
| | 49 | int i; |
| | 50 | |
| | 51 | for (i=0; i < *image_height; i++) |
| | 52 | row_pointers[i] = image_data + i * rowbytes; |
| | 53 | |
| | 54 | png_read_image(png_ptr, row_pointers); |
| | 55 | |
| | 56 | free(row_pointers); |
| | 57 | } |
| | 58 | else |
| | 59 | { |
| | 60 | free(image_data); |
| | 61 | image_data = NULL; |
| | 62 | } |
| | 63 | } |
| | 64 | |
| | 65 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL); |
| | 66 | return image_data; |
| | 67 | } |
| | 68 | else |
| | 69 | { |
| | 70 | png_destroy_read_struct(&png_ptr, NULL, NULL); |
| | 71 | } |
| | 72 | } |
| | 73 | } |
| | 74 | |
| | 75 | return NULL; |
| | 76 | } |