I61 Answer ― Paint Chip


#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, red, grn, blu;
  FILE *image;

  /* check the command line parameters */
  if ( argc != 7 )
  {
    printf("colorChip fileName.ppm nrows ncols red green blue\n");
    return 0;
  }

  /* open the image file for writing in binary mode (see "gotcha!" in Gray Level Images) */
  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 colors from the command line */
  red = getColor( 4, argv );
  grn = getColor( 5, argv );
  blu = 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++ )
    {
      fputc( red, image );  fputc( grn, image );  fputc( blu, image );
    }

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

  return 1;
}

Comments: The version of the program that uses a hex color code can do something like this:

    int val;
    sscanf( argv[4], "%x", &val );
    red = (val>>16)&0xff;
    grn = (val>> 8)&0xff;
    blu =  val     &0xff;