I71 Answer ― Color Waves


#include <stdlib.h>
#include <stdio.h>
#include <math.h>

/* waves

*/

int main(int argc, char *argv[])
{
  int r, nrows, c, ncols, red, grn, blu;
  double redFreq=1.0, grnFreq=2.0, bluFreq=3.0;
  FILE *image;

  /* check the command line parameters */
  if ( argc != 7 )
  {
    printf("colorWaves fileName.ppm nrows ncols redFreq grnFreq bluFreq\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;
  }

  /* get the number of cycles for each color */
  redFreq = atof( argv[4] );
  grnFreq = atof( argv[5] );
  bluFreq = atof( argv[6] );
  if ( redFreq<0.0 || grnFreq<0.0 || bluFreq<0.0 )
  {
    printf("color frequency 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 = (int)(125*cos(2.0*M_PI*c/ncols*redFreq)) + 125;
      grn = (int)(125*cos(2.0*M_PI*c/ncols*grnFreq)) + 125;
      blu = (int)(125*cos(2.0*M_PI*c/ncols*bluFreq)) + 125;
      fputc( red, image ); fputc( grn, image ); fputc( blu, image );
    }

  /* close the file */
  fclose ( image );

  return 1;
}

Comments: You need to be careful that each wave never exceeds the limits of 0 and 255 or the image will show odd effects due to overflow. In the above, the top limit is 250.