我已经和libpng合作了几天了。我已经能够加载和PNG图像并将其转换为RGBA8888,大部分时间。缺少的主要是颜色。我似乎无法弄清楚为什么libpng以灰度级读取数据。
我尝试过使用:
png_set_palette_to_rgb(png_ptr)
和
png_set_gray_to_rgb(png_ptr);
无济于事。我已经几次回顾了关于libpng的文档,我必须遗漏一些明显的东西......
http://www.libpng.org/pub/png/libpng-1.2.5-manual.html#section-3.1
我在这里尝试了这个教程,最后得到了相同的灰度图像:
http://devcry.heiho.net/html/2015/20150517-libpng.html
要完全清楚,我是一个覆盆子pi。我正在使用嵌入式向导及其“externBitmap”功能在运行时动态加载png图像。嵌入式向导需要RGBA8888格式化像素数据。
以下是我用来加载图片文件的代码:
void read_png_file(char* file_name)
{
int y;
png_byte color_type;
png_byte bit_depth;
png_byte channels;
int number_of_passes;
char header[8]; // 8 is the maximum size that can be checked
/* open file and test for it being a png */
FILE *fp = fopen(file_name, "rb");
if (!fp)
abort_("[read_png_file] File %s could not be opened for reading", file_name);
fread(header, 1, 8, fp);
if (png_sig_cmp(header, 0, 8))
abort_("[read_png_file] File %s is not recognized as a PNG file", file_name);
/* initialize stuff */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
abort_("[read_png_file] png_create_read_struct failed");
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
abort_("[read_png_file] png_create_info_struct failed");
if (setjmp(png_jmpbuf(png_ptr)))
abort_("[read_png_file] Error during init_io");
png_init_io(png_ptr, fp);
png_set_sig_bytes(png_ptr, 8);
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);
color_type = png_get_color_type(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
channels = png_get_channels(png_ptr, info_ptr);
printf("%i x %i\n", width, height);
printf("Color type: %d\n", color_type);
printf("Bit Depth: %d\n", bit_depth);
printf("Channels: %d\n", channels);
//number_of_passes = png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
/* read file */
if (setjmp(png_jmpbuf(png_ptr)))
abort_("[read_png_file] Error during read_image");
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_set_palette_to_rgb(png_ptr);
png_read_image(png_ptr, row_pointers);
fclose(fp);
printf("png file read success. Processing file...\n");
}
实际png: Actual png
解码并尝试显示后: After decoding
编辑: 我用更多命令更新了代码:
png_set_palette_to_rgb(png_ptr);
if (png_get_valid(png_ptr, info_ptr,PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png_ptr);
结果图像在这里很难看到,但现在有颜色,图像看起来像现在被拉伸,因为只显示原始图像的一部分: stretched with color now