我正在尝试使用 libpng 读取 PNG 数据,但我无法弄清楚最后一步
你好, 所以在过去的两天里我试图读取 png 像素数据。我需要这方面的帮助。这是我想到的
#include <png.h>
#include <pngconf.h>
#include <stdio.h>
#define BYTES_TO_CHECK 8
// checks the file and returns the file pointer
FILE *check_png(char *file_name) {
char buffer[BYTES_TO_CHECK];
FILE *fP = fopen(file_name, "rb");
if (fP == NULL) {
printf("FILE NOT FOUND!");
exit(0);
}
fread(buffer, 1, BYTES_TO_CHECK, fP);
int check = png_sig_cmp(buffer, 0, BYTES_TO_CHECK);
if (check == 1) {
printf("NOT A PNG");
exit(0);
}
return fP;
}
int main() {
png_structp png_ptr;
png_infop info_ptr;
png_uint_32 height;
png_uint_32 width;
printf("ASCII Generator\nPlease Enter the PNG file name\t");
char file_name[100] = "google.png";
/*scanf("%s", file_name);*/
FILE *fP = check_png(file_name);
png_ptr = png_create_read_struct("1.6.44", NULL, NULL, NULL);
info_ptr = png_create_info_struct(png_ptr);
if (png_ptr == NULL)
printf("ERROR PNG POINTER IS NULL");
else if (info_ptr == NULL)
printf("ERROR INFO POINTER IS NULL");
png_init_io(png_ptr, fP); // initialising input output
png_set_sig_bytes(png_ptr, BYTES_TO_CHECK); // tells that some bytes are already read
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); // reads png
height = png_get_image_height(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
printf("%d %d", height, width);
现在读取像素值时遇到一些问题
png_bytep row_pointer[height];
png_read_image(png_ptr, row_pointer);
返回
Read Error
并且中止
然后我就尝试了
png_bytepp row_pointer = png_get_rows(png_ptr, info_ptr);
它返回一个指向每行像素数据的指针数组,但它都是空的
for (int i = 0; i < height; i++) {
printf("%s", row_pointer[i][50]);
}
我也尝试过 png_read_rows 但无济于事。 请帮帮我,谢谢! :)
首先,您传递了
info_ptr
却没有获得一些有意义的数据。您没有对函数返回进行错误检查。
您为什么不直接查看
libpng
的官方示例,并以此为基础编写您的代码?您显然缺少示例代码的某些部分。
摘自
libpng
的示例代码
png_uint_32 width, height;
int bit_depth, color_type, interlace_method,
compression_method, filter_method;
png_bytep row_tmp;
/* Now associate the recently opened (FILE*) with the default
* libpng initialization functions. Sometimes libpng is
* compiled without stdio support (it can be difficult to do
* in some environments); in that case you will have to write
* your own read callback to read data from the (FILE*).
*/
png_init_io(png_ptr, f);
/* And read the first part of the PNG file - the header and
* all the information up to the first pixel.
*/
png_read_info(png_ptr, info_ptr);
/* This fills in enough information to tell us the width of
* each row in bytes, allocate the appropriate amount of
* space. In this case png_malloc is used - it will not
* return if memory isn't available.
*/
row = png_malloc(png_ptr, png_get_rowbytes(png_ptr,
info_ptr));
您可以访问官方存储库示例并以此为基础编写您的代码。