I06 Answer


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

/* Puzzle I06 -- distance image
|
|
*/

makeDistance( FILE *image, int nrows, int ncols )
{
  int r, c, level ; /* row and col of current pixel */
  double length, dist ;

  /* determine the diagonal length */
  length = sqrt( (double)(nrows*nrows + ncols*ncols) );

  /* write out the pixel data */
  for ( r=0; r<nrows; r++ )
  {
    for ( c=0; c<ncols; c++ )
    {
      dist = sqrt( (double)(r*r + c*c) );
      level = (int)(255*(1.0-dist/length));
      fputc( level, image );
    }
  }
}

void openImage( char *argv[], FILE **image, int *nrows, int *ncols )
{

  /* open the image file for writing */
  if ( (*image = fopen( argv[1], "wb") ) == NULL )
  {
    printf("file %s could not be created\n", argv[1] );
    exit( EXIT_FAILURE );
  }

  *nrows = atoi( argv[2] );
  if ( *nrows < 1 )
  {
    printf("number of rows must be positive\n");
    exit( EXIT_FAILURE );
  }

  *ncols = atoi( argv[3] );
  if ( *nrows < 1 )
  {
    printf("number of columns must be positive\n");
    exit( EXIT_FAILURE );
  }
}

int main( int argc, char *argv[] )
{
  int nrows, ncols ;
  FILE *image;

  /* check the command line parameters */
  if ( argc != 4 )
  {
    printf("grayDist fileName.pgm nrows ncols\n");
    return 0;
  }

  /* Open the image file, get number of rows and columns */
  openImage( argv, &image, &nrows, &ncols );

  /* write out the PGM Header information */
  fprintf( image, "P5 ");
  fprintf( image, "# Created by makeDistance\n");

  /* width, height, number of gray levels */
  fprintf( image, "%d %d %d ", ncols, nrows, 255 );

  /* Create the Image */
  makeDistance( image, nrows, ncols );

  /* close the file */
  fclose ( image );
  return 1;
}

Comments: The openImage() function simplifies main().

back