c - 使用 libpng 过滤器

标签 c libpng

我想用 libpng 读取 PNG 文件,并且想使用过滤器 png_set_rgb_to_gray_fixed 将 RGB 值转换为灰度。原始图像每个 channel 有 8 位,因此每个像素有 3 个字节。我预计输出为每像素 8 位。然而 png_get_rowbytes 告诉我行大小是 3*宽度。我做错了什么?

这是我的代码(为了简洁起见,我删除了错误检查代码):

FILE *fp = fopen(filename,"rb");
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
png_infop info_ptr = png_create_info_struct(png_ptr);    
png_infop end_info = png_create_info_struct(png_ptr);
png_init_io(png_ptr, fp);
png_uint_32 width,height;
int color_depth,color_type, interlace_type, compression_type, filter_method;    
png_read_info(png_ptr, info_ptr);    
png_get_IHDR(png_ptr, info_ptr, &width, &height,
             &color_depth, &color_type, &interlace_type,
             &compression_type, &filter_method);
assert(color_type == PNG_COLOR_TYPE_RGB); 
png_set_rgb_to_gray_fixed(png_ptr, 3,-1,-1);

int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
assert(rowbytes == width ); // FAILS: rowbytes == 3*width

最佳答案

您需要调用png_read_update_info :

png_read_update_info() updates the structure pointed to by info_ptr to reflect any transformations that have been requested. For example, rowbytes will be updated to handle expansion of an interlaced image with png_read_update_info().

所以:

png_set_rgb_to_gray_fixed(png_ptr, 3,-1,-1);
png_read_update_info(png_ptr, info_ptr);
int rowbytes = png_get_rowbytes(png_ptr, info_ptr);

关于c - 使用 libpng 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14662566/

相关文章:

c++ - PNG++ 读取像素颜色值

c - 使用C编程显示图像文件

png - 使用CImg加载PNG

c - fclose 上的段错误

c - 状态 0xC0000121 - 删除文件

c++ - DEBUG : During Hook procedure call , 它显示 vsjitdebugger.exe 错误

c++ - 奇怪的 VS2013 调试器行为与 libpng 1.6.25

c - gcc 静态库链接与动态链接

c - 执行recv()和send()winsock

c++ - Libharu 使用 windows.h 创建有关 pngtest.c 的错误