
/* This program reads a jpeg color image, uses
   'djpeg' command to convert it into ppm format, and then
   skips the header to store the image in binary into rgb 2D arrays */
/* Image size is 412X500, can be changed to other sizes by modifying 
   the code and re-compiling. */

#include <stdio.h>

main()
{

unsigned char imager[412][500]; /* Each pixel is a byte, best represented using
                                  unsigned char data type */
unsigned char imageg[412][500]; /* Each pixel is a byte, best represented using
                                  unsigned char data type */
unsigned char imageb[412][500]; /* 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 rows, cols, highests
                                    intensity of the image */

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

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

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

 for (i = 0; i< rows; i++)
 {
 for (j = 0; j< cols; j++) {
 fread(&imager[i][j],1,1,fr); /* After the header, pgm has raw image */
 fread(&imageg[i][j],1,1,fr); /* After the header, pgm has raw image */
 fread(&imageb[i][j],1,1,fr); /* After the header, pgm has raw image */
}
}

fclose(fr);

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

for (i=10;i<100;i++)
for (j=10;j<100;j++)
{
imager[i][j]=50;
imageg[i][j]=20;
imageb[i][j]=85;
}

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

/* With the header first and then the image in binary. note, width first, then height */
fprintf(fw,"P6\n%d %d\n255\n",cols,rows);

/* write each row, just the way we read each row */
 for (i = 0; i<rows; i++)
 for (j = 0; j<cols; j++)
{
 fwrite(&imager[i][j],1,1,fw);
 fwrite(&imageg[i][j],1,1,fw);
 fwrite(&imageb[i][j],1,1,fw);
}


fclose(fw);

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

}


