/*********************************************************/ /* program 28: program 1 rewrite */ /*********************************************************/ #include "sys/file.h" #include "math.h" main(argc,argv) short int argc; /* number of arguments */ char *argv[]; /* argument values */ { unsigned char *ir,*ig,*ib; unsigned char *or,*og,*ob; long int x,y; long int fpi,fpo; long int xsize,ysize; long int planes; long int sgi_type; long int depth; float scale; char in_file[256],out_file[256]; if (argc < 4) { printf("Usage: prog28 \n"); } else { sscanf(argv[1],"%s",in_file); sscanf(argv[2],"%s",out_file); sscanf(argv[3],"%d",&depth); if ((depth < 1) || (depth > 7)) { printf("invalid depth request: %d\n",depth); } else { /* open the input image file */ fpi = open(in_file,O_RDONLY); if (fpi <= 0) { printf("cannot open input file: %s\n",in_file); } else { /* read the input image file header */ read_sgi_header(fpi,&xsize,&ysize,&planes,&sgi_type); /* allocate input and output memory buffers */ ir = (unsigned char *) malloc (xsize*ysize); ig = (unsigned char *) malloc (xsize*ysize); ib = (unsigned char *) malloc (xsize*ysize); or = (unsigned char *) malloc (xsize*ysize); og = (unsigned char *) malloc (xsize*ysize); ob = (unsigned char *) malloc (xsize*ysize); /* read the input image data */ read_sgi_data(fpi,xsize,ysize,planes,sgi_type,ir,ig,ib); close(fpi); /* calculate the scale factor that will reduce 8-bit values (0-255, inclusive) to evenly spaced values of 0-255 for the requested depth resolution. */ /* example: if depth = 2, values are 0, 85, 171, and 255 */ scale = 255.0 / (powf (2.0, (float)depth) - 1.0); /* reduce depth resolution by generating new 8-bit pixel values */ for (y = 0; y < ysize; y = y++) { for (x = 0; x < xsize; x = x++) { or[(y*xsize)+x] = (ir[(y*xsize)+x] >> (8 - depth)) * scale; og[(y*xsize)+x] = (ig[(y*xsize)+x] >> (8 - depth)) * scale; ob[(y*xsize)+x] = (ib[(y*xsize)+x] >> (8 - depth)) * scale; } } /* create and open the output image file */ fpo = open(out_file,O_WRONLY|O_CREAT|O_TRUNC,0666); if (fpo <= 0) { printf("cannot open input file: %s\n",in_file); } else { /* write the output image */ write_sgi_header(fpo,xsize,ysize,planes,sgi_type); write_sgi_data(fpo,xsize,ysize,planes,or,og,ob,sgi_type); close(fpo); } /* free memory buffers */ free (ir); free (ig); free (ib); free (or); free (og); free (ob); } } } }