Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
unsigned char **image; /* 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 */
int userrow,
usercolmn;
char filename[35],
filename2[50],
filename3[50],
outfile[70],
commanda[70];
strcpy (commanda, "djpeg -outfile image.pgm ");
printf ("Please enter filename of image:\n");
scanf ("%s", filename);
strcpy(filename2, filename);
strcpy(filename3, filename);
strcat(filename, ".jpg");
strcat(commanda, filename);
printf ("%s", commanda);
printf ("Enter first dimension of image:");
scanf ("%d", &userrow);
printf ("Enter second dimension of image:");
scanf ("%d", &usercolmn);
system(commanda);
fr=fopen("image.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 */
image = (unsigned char *) calloc (userrow, sizeof(unsigned char *) ) ;
/* above statement allocates 'row' number of pointers that
point to each row of the array */
/* Allocates memory for each row of image seperately, pointed by above row-number of pointers*/
for (i = 0; i< userrow; i++)
image[i] = (unsigned char *) calloc (usercolmn, sizeof(unsigned char *) ) ;
fread(image,1,usercolmn*userrow,fr); /* After the header, pgm has raw image */
fclose(fr);
/* now, lets modify the pixels.. */
for (i=256;i<userrow-200;i++)
for (j=256;j<usercolmn-200;j++)
image[i][j]=255;
strcat (filename2, "_modified.pgm");
/* We will write the pgm file first */
fw=fopen(filename2, "w");
strcat (filename3, "_modified.jpg");
strcpy(outfile, "cjpeg -outfile ");
strcat(outfile, filename3);
strcat(outfile, filename2);
/* With the header first and then the image in binary */
fprintf(fw,"P5\n%d %d\n255\n",usercolmn,userrow);
fwrite(image,1,usercolmn,fw);
fclose(fw);
/*The 'cjpeg' command converts the pgm file into jpeg, which can be opened by any browser*/
system(outfile);
for (i = 0; i< userrow; i++)
free(image[i]);
}
[/tag]