#include <stdlib.h>
#include <stdio.h>
/* randomPixels -- create an image with pixels of random color
The red, green, and blue values for each pixel are choosen
randomly and independently.
*/
int main(int argc, char *argv[])
{
int r, nrows, c, ncols, red, grn, blu;
FILE *image;
/* check the command line parameters */
if ( argc != 4 )
{
printf("colorChip fileName.ppm nrows ncols\n");
return 0;
}
/* open the image file for writing in binary mode */
if ( (image = fopen( argv[1], "wb") ) == NULL )
{
printf("file %s could not be created\n", argv[1]);
return 0;
}
nrows = atoi( argv[2] );
if ( nrows < 1 )
{
printf("number of rows must be positive\n");
return 0;
}
ncols = atoi( argv[3] );
if ( ncols < 1 )
{
printf("number of columns must be positive\n");
return 0;
}
/* write out the PPM Header information */
fprintf( image, "P6 ");
fprintf( image, "%d %d %d ", ncols, nrows, 255 );
srand( time(NULL) );
/* write out the pixel data */
for ( r=0; r<nrows; r++ )
for ( c=0; c<ncols; c++ )
{
red = rand()%256;
grn = rand()%256;
blu = rand()%256;
fputc( red, image ); fputc( grn, image ); fputc( blu, image );
}
/* close the file */
fclose ( image );
return 1;
}
Comments:
Using integer modulo division with rand()
does not produce the best random integers.
You might want to use randInt() from section B of the puzzles.