/*By C. Kambhamettu, 11/9/06 */ 

/* This program reads a jpeg gray level image, uses
   'djpeg' command to convert it into pgm format, and then
   skips the header to store the image in binary into 2D array */
/* Image size is 512X512, can be changed to other sizes in the
   program, and re-compiled. Next class talks about dynamic allocation 
   where you don't need to change the program. It will be user
   input. */ 

#include <stdio.h>

void main()
{

unsigned char image[512][512]; /* Each pixel is a byte, best represented using
                                  unsigned char data type */
FILE *fr; /* File pointer to open the image */
FILE *fw; /* File pointer to write the image */

int i,j;
int rows,cols,highest_intensity; /* The pgm format header includes cols, rows, highest
                                    intensity of the image */

system("djpeg -outfile lenabrite.pgm lenabrite.jpg"); /* djpeg is a unix command, which
                                       converts jpeg to other image formats - see man djpeg */

fr=fopen("lenabrite.pgm","r");  /* Open the pgm file - this is the image written using above command */

fscanf(fr,"P5\n%d %d\n%d\n",&cols,&rows,&highest_intensity); /* P5 represents binary format of 
                                     a  pgm file */

fread(image,1,512*512,fr); /* After the header, pgm has raw image */

fclose(fr);

/* now, lets modify the pixels.. */

for (i=256;i<rows-200;i++)
for (j=256;j<cols-200;j++)
image[i][j]=255;

/* We will write the pgm file first */
fw=fopen("lenabrite_modified.pgm","w");

/* With the header first and then the image in binary */
fprintf(fw,"P5\n%d %d\n255\n",cols,rows);
fwrite(image,1,512*512,fw);
fclose(fw);

/*The 'cjpeg' command converts the pgm file into jpeg, which can be opened by any browser*/
 
system("cjpeg -outfile lenabrite_modified.jpg lenabrite_modified.pgm");

}


