pgm文件是一种可移植灰度图片,有P2和P5两种格式,今天给大家分享一种P2格式下写入pgm文件数据的方法。
int write_ASCII(FILE *outputFile, pgmImage *pgm)
{
/* write magic number, size & gray value */
size_t nBytesWritten = fprintf(outputFile, "P2\n%d %d\n%d\n", (*pgm).width, (*pgm).height, (*pgm).maxGray);
/* check that dimensions wrote correctly */
if (nBytesWritten < 0)
{
/* failed size sanity check */
/* free up the memory */
free_pgm(pgm);
/* return error code */
return ERROR_OUTPUT_FAILED;
} /* dimensional write failed */
/* pointer for efficient write code */
for (unsigned char *nextGrayValue = (*pgm).imageData; nextGrayValue < (*pgm).imageData + (*pgm).nImageBytes; nextGrayValue++)
{
/* per gray value */
/* get next char's column */
int nextCol = (nextGrayValue - (*pgm).imageData + 1) % (*pgm).width;
/* write the entry & whitespace */
nBytesWritten = fprintf(outputFile, "%d%c", *nextGrayValue, (nextCol ? ' ' : '\n'));
/* sanity check on write */
if (nBytesWritten < 0)
{
/* failed size sanity check */
/* free up the memory */
free_pgm(pgm);
/* return error code */
return ERROR_OUTPUT_FAILED;
} /* data write failed */
} /* per gray value */
return FUNCTION_SUCCESS;
}