#include <stdlib.h>
#include <stdio.h>
int getColor( int arg, char *argv[] )
{
int value;
value = atoi( argv[arg] );
if ( value < 0 || value > 255 )
{
printf("color level %s must be between 0 and 255\n", argv[arg]);
exit( EXIT_FAILURE );
}
return value;
}
int main(int argc, char *argv[])
{
int r, nrows, c, ncols;
int redL, grnL, bluL; /* left edge RGB */
int red, grn, blu; /* extrapolated RGB */
FILE *image;
/* check the command line parameters */
if ( argc != 7)
{
printf("gradientOne fileName.ppm nrows ncols redL greenL blueL\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;
}
redL = getColor( 4, argv );
grnL = getColor( 5, argv );
bluL = getColor( 6, argv );
/* write out the PPM Header information */
fprintf( image, "P6 ");
fprintf( image, "%d %d %d ", ncols, nrows, 255 );
/* write out the pixel data */
for ( r=0; r<nrows; r++ )
for ( c=0; c<ncols; c++ )
{
red = redL*(ncols-c)/ncols;
grn = grnL*(ncols-c)/ncols;
blu = bluL*(ncols-c)/ncols;
fputc( red, image ); fputc( grn, image ); fputc( blu, image );
}
/* close the file */
fclose ( image );
return 1;
}
Comments: This the the cruicial part of the program:
/* write out the pixel data */
for ( r=0; r<nrows; r++ )
for ( c=0; c<ncols; c++ )
{
red = redL*(ncols-c)/ncols;
grn = grnL*(ncols-c)/ncols;
blu = bluL*(ncols-c)/ncols;
fputc( red, image ); fputc( grn, image ); fputc( blu, image );
}
The amount of red at column c is
the amount of red at the left edge of the image multiplied by the fraction
of the width that is to the right of column c:
(ncols-c) --------- ncols
The fraction varies from 1.0 at the left edge to 0.0 at the right edge.