【问题标题】:can not read png file with libpng无法使用 libpng 读取 png 文件
【发布时间】:2012-04-18 05:00:25
【问题描述】:

我是 libpng 的新手,文档让我很困惑。 以下是我的代码不起作用,我看不出原因。 有人可以指出我正确的方向吗?或建议不同的(“更简单”)库?

我是如何理解 libpng 的:

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

  2. png_create_read_struct创建png_structp

  3. png_create_info_struct创建png_infop

  4. 分配空间

  5. 读取数据

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

【问题讨论】:

  • png_create_read_struct 失败。编译器不写任何错误它什么都不做
  • 怎么样?你必须更具体。
  • 我用if (!png_ptr) printf("png_create_read_struct failed"); 看看有什么问题。
  • 显然无法分配结构。您使用的是什么编译器/等?
  • VS 2008 express,会不会是错误的include libpng文件到编译器造成的?我遇到了一点麻烦。

标签: c libpng


【解决方案1】:

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

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 的错误报告应该可以提供洞察力。

【讨论】:

    【解决方案2】:

    显然,libpng 没有关于在哪里/如何读取图像块的信息。使用:

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

    【讨论】:

    • 他仍然需要png_ptr 为非空才能使用png_init_io
    • @sixlettervariables:你是对的,但他很快就会面临这个问题 :-)
    猜你喜欢
    • 2021-04-11
    • 2012-01-11
    • 2019-07-17
    • 2016-02-24
    • 2017-10-29
    • 2012-06-05
    • 2014-03-30
    • 2012-05-13
    相关资源
    最近更新 更多