user1281071
user1281071

Reputation: 895

can not read png file with libpng

I am new to libpng and the documentation is really confusing for me. Below is my code which is not working and I do not see the reason why. Can someone point me to right direction? or suggest different ( "easier" ) library?

how I understand libpng:

  1. open the file with fopen in rb mode

  2. create png_structp with png_create_read_struct

  3. create png_infop with png_create_info_struct

  4. allocate space

  5. read data

    #include <stdio.h>
    #include <png.h>
    
    int main( int argc, char **argv )
    {
        int x, y;
        int height, width;
    
        png_structp png_ptr;
        png_infop info_ptr;
    
        png_bytep *row_pointers;
    
        FILE *fp = fopen( "test.png", "rb");
        {
            if (!fp)
                printf("File could not be opened for reading");
    
            png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    
            info_ptr = png_create_info_struct(png_ptr);
    
            png_read_info(png_ptr, info_ptr);
            width = png_get_image_width(png_ptr, info_ptr);
            height = png_get_image_height(png_ptr, info_ptr);
    
            row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
            for (y=0; y<height; y++)
                row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png_ptr,info_ptr));
    
            png_read_image(png_ptr, row_pointers);
    
            fclose(fp);
        }
    
        for (y=0; y<height; y++) 
        {
            png_byte *row = row_pointers[y];
            for (x=0; x<width; x++) 
            {
                png_byte* ptr = &(row[x*4]);
                printf("Pixel at position [ %d - %d ] has RGBA values: %d - %d - %d - %d\n", x, y, ptr[0], ptr[1], ptr[2], ptr[3]);
            }
        }
    }
    

Upvotes: 1

Views: 4832

Answers (2)

mlepage
mlepage

Reputation: 2472

I similarly had failure in png_create_read_struct. It is difficult to debug without further info (in my case, stderr goes nowhere), but fortunately you can provide your own error and warning functions:

void user_error_fn(png_structp png_ptr, png_const_charp error_msg);
void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg);

Using this, libpng printed helpful errors stating that the application was using a different version of the header than the libpng found at runtime. Mystery solved.

So while individual issues may differ, using libpng's error reporting should provide insight.

Upvotes: 5

udslk
udslk

Reputation: 529

Obviously, there is no information passed to libpng about where/how to read image chunk. Use:

... png_init_io(png_ptr, fp); png_read_info..

Upvotes: 2

Related Questions