无法用libpng读取png文件

我是libpng的新手,文档对我来说真的很混乱。 下面是我的代码不起作用,我没有看到原因。 有人能指出我正确的方向吗? 或建议不同的(“更容易”)图书馆?

我怎么理解libpng:

  1. rb模式下使用fopen打开文件

  2. 使用png_create_read_struct创建png_create_read_struct

  3. 使用png_create_info_struct创建png_create_info_struct

  4. 分配空间

  5. 读数据

     #include  #include  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]); } } } 

我同样在png_create_read_struct中失败了。 没有进一步的信息很难调试(在我的情况下,stderr无处可去),但幸运的是,你可以提供自己的错误和警告function:

 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); 

使用这个,libpng打印了有用的错误,指出应用程序使用的标头版本与运行时发现的libpng不同。 谜团已揭开。

因此,虽然个别问题可能有所不同,但使用libpng的错误报告应提供洞察力。

显然,没有信息传递给libpng关于在何处/如何读取图像块。 使用:

… png_init_io(png_ptr,fp); png_read_info ..