#include <stdio.h>
#include <stdlib.h>
/* Puzzle I02 -- create an image file with all pixels the same level
|
| The name of the file, the number of rows and number of columns,
| and the gray level are specified on the command line.
|
| This version does the image creation in a function.
|
*/
void writePixels( FILE *image, int nrows,
int ncols, int grayLevel )
{
int r, c;
/* all pixels are the same graylevel */
for ( r=0; r<nrows; r++ )
for ( c=0; c<ncols; c++ )
fputc( grayLevel, image );
}
int main(int argc, char *argv[])
{
int nrows, ncols, grayLevel;
FILE *image;
/* check the command line parameters */
if ( argc != 5 )
{
printf("makeGray fileName.pgm nrows ncols grayLevel\n");
return 0;
}
nrows = atoi( argv[2] );
if ( nrows < 1 )
{
printf("number of rows must be positive\n");
return 0;
}
ncols = atoi( argv[3] );
if ( nrows < 1 )
{
printf("number of columns must be positive\n");
return 0;
}
grayLevel = atoi( argv[4] );
if ( !(grayLevel >= 0 && grayLevel <=255) )
{
printf("grayLevel must be between 0 and 255\n");
return 0;
}
/* open the image file for writing */
if ( (image = fopen( argv[1], "wb") ) == NULL )
{
printf("file %s could not be created\n", argv[1]);
return 0;
}
/* write out the PGM Header information */
fprintf( image, "P5 ");
fprintf( image, "# Created by makeGray\n");
fprintf( image, "%d %d %d ", ncols, nrows, 255 );
/* Write out all the pixels */
writePixels( image, nrows, ncols, grayLevel );
/* close the file */
fclose ( image );
return 1;
}
Comments:
1. Study how the function definition:
void writePixels( FILE *image, int nrows,
int ncols, int grayLevel )
and the function call
writePixels( image, nrows, ncols, grayLevel );
are coordinated.
2. In refactoring the program, you might have decided to put the code that writes the image header into the function. This would have been OK.