我正在尝试使用libpng库读取和写入png文件。我可以进行写操作,但似乎无法进行读操作。为了简化起见,我现在要将整个图像加载到内存中,然后尝试索引到每一行以访问数据。这是我的问题开始的地方。我似乎在任何文档中都找不到要迭代的数据量以及数据的布局方式。
每三个数字是一个像素(R,G,B)吗?
我知道,如果字节数为600,则每行有n个以上的列号。
这是我的代码:
#include <png.h>
#include <stdio.h>
int main() {
FILE *fp = fopen("example.png", "rb");
if (!fp) {
printf("There was something wrong with your file..\n");
return 0;
}
int row = 0, width = 0, height = 0; png_structp png_ptr = NULL; png_infop info_ptr = NULL;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png_ptr) {
printf("There was something wrong with creating the read struct..\n");
return 0;
}
info_ptr = png_create_info_struct(png_ptr);
if(!info_ptr) {
printf("There was something wrong with creating the info struct..\n");
return 0;
}
png_init_io(png_ptr, fp);
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);
png_bytep row_pointers[height];
for (row = 0; row < height; row++)
row_pointers[row] = NULL;
for (row = 0; row < height; row++)
row_pointers[row] = png_malloc(png_ptr, png_get_rowbytes(png_ptr,info_ptr));
png_read_image(png_ptr, row_pointers);
int number = 0;
png_uint_32 rowbytes = png_get_rowbytes(png_ptr, info_ptr);
printf("Number of bytes per row: %d\n", rowbytes);
for (row = 0; row < height; row++) {
for (int column = 0; column < width; column++) {
printf("%d\n", row_pointers[0][column]);
}
printf("\n");
}
png_read_end(png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(fp);
return 0;
}
谢谢。