I28 Answer -- Add a Constant


#include <stdlib.h>
#include <stdio.h>
#include "basicImage.c"  

void addConst( image img, unsigned char constant )
{
  int r, c, value ;
  
  for ( r=0; r<img.nrows; r++ )
    for ( c=0; c<img.ncols; c++ )
    {
      value = getPixel( img, r, c ) + constant ;
      if      ( value > 255 ) value = 255;
      else if ( value < 0   ) value = 0;
      setPixel( img, r, c, (unsigned char)value );
    }
}

int main ( int argc, char* argv[] )
{
  image img;
  int   constant ;
  
  if ( argc != 4 )
  {
    printf("addConst oldImage newImage constant\n");
    system( "pause" );
    exit( EXIT_FAILURE );
  }
  
  constant = atoi( argv[3] );
  
  /* read in the old image */
  readPGMimage( &img, argv[1]);
  
  /* add in the constant value */
  addConst( img, (unsigned char)constant ) ;
  
  /* write the image to disk and free memory */
  writePGMimage( img, argv[2]);
  freeImage( &img );
  system( "pause" );
}

Comments: It is important to "clamp" the highest pixel value at 255, otherwise overflow problems will occur and the brightened image may get corrupted with many black pixels. The low value must be clamped at zero, otherwise unintended bright pixels might result.

Sometimes brightening an image makes it look better. However, no new information is contained in the brighter image, and (if clamping has occured) information might be lost.