I73 Answer ― Color Circles


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

int main(int argc, char *argv[])
{
  int r, nrows, c, ncols;
  double redCycles, grnCycles, bluCycles;
  int red, grn, blu ;
  FILE *image;

  /* check the command line parameters */
  if ( argc != 7 )
  {
    printf("makeCircles fileName.ppm nrows ncols redCycles grnCycles bluCycles\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] );
  ncols     = atoi( argv[3] );
  redCycles = atof( argv[4] );
  grnCycles = atof( argv[5] );
  bluCycles = atof( argv[6] );

  /* write out the PPM Header information */
  fprintf( image, "P6 ");
  fprintf( image, "%d %d %d ", ncols, nrows, 255 );

  /* find the maximum distance from the center of the image */
  double radius = sqrt( nrows*nrows + ncols*ncols )/2.0 ;
  double dist;
  double cntR = nrows/2.0, cntC = ncols/2.0;

  /* write out the pixel data */
  for ( r=0; r<nrows; r++ )
    for ( c=0; c<ncols; c++ )
    {
      dist = sqrt( (r-cntR)*(r-cntR) + (c-cntC)*(c-cntC)) ;
      red  = 125 + 125*cos( redCycles*2*M_PI*(dist/radius));
      grn  = 125 + 125*cos( grnCycles*2*M_PI*(dist/radius));
      blu  = 125 + 125*cos( bluCycles*2*M_PI*(dist/radius));
      fputc( red, image );  fputc( grn, image );  fputc( blu, image );
    }

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

  return 1;
}

Comments: The programming is fairly easy. It is the math that worries most people.

For the variation that uses a crazy distance function, try just removing both sqrt() from the above, or perhaps replacing both with log or some other function. There are many things you can do. You will have to beware of overflow problems, however. (Actually, sometimes overflow mistakes result in interesting pictures.)