#include <stdlib.h> #include <stdio.h> #include "basicImage.c" /* Use the version that does not include readPGMimage() */ void readPGMimage( image *img, char *filename ) { FILE *file; char buffer[1024]; int nrows, ncols, ngray ; /* open the image file for reading binary */ if ( (file = fopen( filename, "rb") ) == NULL ) { printf("readImage(): file %s could not be opened\n", filename ); exit( EXIT_FAILURE ); } /* read signature on first line */ if ( fscanf( file, "%s", buffer ) != 1 ) { printf("error in image header: no signature\n" ); exit( EXIT_FAILURE ); } if ( strncmp( buffer, "P5", 2 ) != 0 ) { printf("readPGMimage(): file %s is not a PGM file\n", filename ); printf("Signature: %s\n", buffer ); exit( EXIT_FAILURE ); } /* skip over comment lines */ int moreComments = 1, ch; while ( moreComments ) { /* skip over possible white space */ while ( (ch=fgetc(file)) && isspace(ch) ); if ( ch=='#' ) { /* comments are required to end with line-feed */ fgets( buffer, 1024, file ); } else { moreComments = 0; ungetc( ch, file ); } } /* get ncols, nrows, ngray and eat rhe required single white space */ int count = fscanf( file, "%d %d %d", &ncols, &nrows, &ngray ); if ( count != 3 ) { printf("error in image header\n" ); exit( EXIT_FAILURE ); } fgetc(file); if ( ngray != 255 ) { printf("readPGMimage(): file %s is %d, not 8 bits per pixel\n", filename, ngray ); exit( EXIT_FAILURE ); } /* construct an image structure of the appropriate size */ if ( !newImage( img, nrows, ncols ) ) { printf("readPGMimage(): newImage failed\n" ); exit( EXIT_FAILURE ); } /* read the pixel data */ fread( img->pixels, 1, img->nrows*img->ncols, file ); /* close the file */ fclose( file ); } int main ( int argc, char* argv[] ) { image img ; if ( argc != 3 ) { printf("copyImage oldImage newImage\n"); system( "pause" ); exit( EXIT_FAILURE ); } /* read in the old image */ readPGMimage( &img, argv[1]); /* write the image to disk and free memory */ writePGMimage( img, argv[2]); freeImage( &img ); system( "pause" ); }
Comments: