我编写了以下代码来生成黑白PNG图像,其中每个像素的值为16位(0 =黑色,0xFFFF =白色)。它是一个简单的640x480测试图像,其中所有线条都是相同的,左边的每条线都有最大的黑色,向右倾斜到白色。由于每行的宽度为640像素,我预计会看到一个几乎全黑的图像,右边的白色最大值达到640/65535。相反,我得到的图像与值0x00ff和0x01ff相对应地达到纯白色2次。这表明libpng不使用每个像素的最重要字节。谁能告诉我哪里错了?无论如何,感谢大家。再见
系统和编译细节:
系统MacBook Pro(Retina,15“,2013年底),OS X 10.11.6
PNG> gcc --version
配置为: - prefix = / Applications / Xcode.app / Contents / Developer / usr --with-gxx-include-dir = / Applications / Xcode.app / Contents / Developer / Platforms / MacOSX.platform / Developer / SDKs / MacOSX10.12.sdk / usr / include / c ++ / 4.2.1 Apple LLVM 8.0.0版(clang-800.0.42.1)目标:x86_64-apple-darwin15.6.0线程模型:posix InstalledDir:/ Applications / Xcode。应用/内容/开发商/工具链/ XcodeDefault.xctoolchain在/ usr / bin中
PNG> gcc -I / opt / X11 / include / -L / opt / X11 / lib / -l png -l z writeTest16bit.c
/* This is the test code upper described */
#include <png.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define ERROR -1
#define GOTO_ERROR {line = __LINE__; goto error;}
#define width 640
#define height 460
#define bit_depth 16
unsigned short int image[height][width];
void setBitMapImageGray (void);
int main (int argc, char **argv)
{
char *pngFileName = "file.png";
FILE *pngFile = NULL;
png_structp pngStruct = NULL;
png_infop pngInfo = NULL;
int line = __LINE__;
int i;
setBitMapImageGray ();
if (NULL == (pngFile = fopen (pngFileName, "wb"))) GOTO_ERROR;
if (NULL == (pngStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL))) GOTO_ERROR;
if (NULL == (pngInfo = png_create_info_struct (pngStruct))) GOTO_ERROR;
// setting long jump: posponed
png_init_io(pngStruct, pngFile);
png_set_IHDR (pngStruct, pngInfo, width, height, bit_depth,
PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_write_info (pngStruct, pngInfo);
for (i=0; i<height; i++)
png_write_row (pngStruct, (png_const_bytep)&image[i][0]);
png_write_end (pngStruct, NULL);
png_destroy_write_struct (&pngStruct, (png_infopp)NULL);
fclose (pngFile);
return 0;
error:
printf ("Error in line %d\n", line);
if (pngStruct) png_destroy_write_struct (&pngStruct, (png_infopp)NULL);
if (pngFile) fclose (pngFile);
return (ERROR);
}
void setBitMapImageGray (void)
{
int x,y;
unsigned short int const black=0, step=0x10000/width;
for (y=0; y<height; y++)
for (x=0; x<width; x++)
// image[y][x] = 0xFF00;
image[y][x] = x;
}
你几乎是对的 - 它没有忽略高字节,但你有一个字节序问题。
如果你在png_set_swap()
之后添加png_write_info()
,你的代码工作正常:
...
png_set_IHDR (pngStruct, pngInfo, width, height, bit_depth,
PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_write_info(pngStruct, pngInfo);
png_set_swap(pngStruct); // <--- THIS LINE ADDED
...
关键词:PNG,libpng,16位,16位,灰度,字节序,字节顺序,字节顺序,小端,大端,写,图像,图像处理,C。