Question

i've been struggling to get libpng to work on my opengl c++ program. I am trying to load png's as textures. I have downloaded the libpng16 source code and built it using Visual Studio 2010. I have correctly linked the lib files and included the png.h file.

When I build my project, libpng prints "libpng error: read error" to my console and nothing else. I have tried all the solutions i've found on the internet including changing my runtime configurations on the libpng project to match my project that im using it on.

The error occurs at the png_read_png function:

    FILE * file = fopen(filename,"r");
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING , NULL ,NULL , NULL );
if ( png_ptr == NULL )
{
printf ( "Could not initialize libPNG ’s read struct.\n" ) ;
exit(-1);
}
png_infop png_info_ptr = png_create_info_struct(png_ptr) ;
if ( png_info_ptr == NULL )
{
printf ("Could not initialize libPNG ’s info pointer.\n");
exit ( -1) ;
}
if (setjmp(png_jmpbuf(png_ptr)))
{

  printf ( "LibPNG encountered an error.\n" ) ;
 png_destroy_read_struct(&png_ptr, &png_info_ptr ,NULL );
  exit( -1);
}

png_init_io ( png_ptr , file );
png_read_png ( png_ptr , png_info_ptr , 0 , NULL ) ;
png_uint_32 png_width = 0;
png_uint_32 png_height = 0;
int bits = 0;
int colour_type = 0;
png_get_IHDR ( png_ptr , png_info_ptr , & png_width , & png_height ,& bits , & colour_type ,NULL , NULL , NULL );
const unsigned BITS_PER_BYTE = 8;
unsigned bytes_per_colour = (unsigned)bits/ BITS_PER_BYTE ;
unsigned colours_per_pixel;

if ( colour_type == PNG_COLOR_TYPE_RGB)
{
  colours_per_pixel = 3;
}
else
{
printf ( " Colour types other than RGB are not supported." ) ;
exit ( -1) ;
}
printf ( "png_width = %d, png_height = %d , bits = %d, colour type = %d. \n" , png_width , png_height , bits , colour_type );
unsigned char * data = new unsigned char [ png_width * png_height * colours_per_pixel * bytes_per_colour];
png_bytepp row_pointers = png_get_rows ( png_ptr , png_info_ptr ) ;
unsigned index = 0;
for ( unsigned y = 0; y < png_height ; y ++)
{
  unsigned x = 0;
  while ( x < png_width * colours_per_pixel * bytes_per_colour) {
data [index++] = row_pointers [y][x++];
data [index++] = row_pointers [y][x++];
data [index++] = row_pointers [y][x++];
  }
}

I have made sure that the correct filename is passed and I have tried multiple different PNG's

Any assistance with this will be appreciated

Thanks

Was it helpful?

Solution

On Windows you must open image files in binary mode, otherwise any occurance of a sequence of bytes, that could be interpreted as will be converted into a single . Right now you're opening the file in standard mode, which is text mode. You can open in binary mode, by adding a 'b' to the mode string, i.e.

FILE * file = fopen(filename,"rb");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top