-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpbm.c
116 lines (91 loc) · 2.95 KB
/
pbm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "pbm.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
PPMImage * read_ppmfile( const char * infilename ) {
FILE * infile;
char intype[3];
int w, width, h, height, maxval;
if( (infile = fopen( infilename, "r" )) == NULL ) {
perror("fopen()");
exit(-1);
}
if( fscanf( infile, "%2s %d %d %d", intype, &width, &height, &maxval ) == EOF ) {
fprintf(stderr, "Error reading input file.\n");
exit(-1);
}
if ( strcmp(intype, "P3") ) {
fprintf(stderr, "Wrong input file type! Magic number, %s, should be 'P3'\n",
intype );
exit(-1);
}
PPMImage * ppm = new_ppmimage( width, height, maxval );
for( h=0; h<height; h++ ){
for ( w=0; w<width; w++ ){
if( fscanf( infile, "%u %u %u",
&ppm->pixmap[0][h][w],
&ppm->pixmap[1][h][w],
&ppm->pixmap[2][h][w] )
== EOF ) {
fprintf(stderr, "Error reading input file.\n");
exit(-1);
}
}
}
fclose( infile );
return ppm;
}
void write_ppmfile( PPMImage *ppm, const char *filename ){
FILE * outfile;
if( (outfile = fopen( filename, "w" )) == NULL ) {
perror("fopen()");
exit( -1 );
}
//write ppm header
fprintf(outfile, "P3\n%d %d\n%d\n", ppm->width, ppm->height, ppm->max);
//write ppm pixmap
for( int h=0; h<ppm->height; h++ ){
for ( int w=0; w<ppm->width; w++ ){
fprintf(outfile, "%d %d %d ",
ppm->pixmap[0][h][w],
ppm->pixmap[1][h][w],
ppm->pixmap[2][h][w] );
}
fprintf(outfile, "\n"); //newline after each row
}
fclose( outfile );
}
void write_pbmfile( PBMImage *pbm, const char * filename ) {
FILE * outfile;
if( (outfile = fopen( filename, "w" )) == NULL ) {
perror("fopen()");
exit( -1 );
}
//write pbm header
fprintf(outfile, "P1\n%d %d\n", pbm->width, pbm->height);
//write pbm pixmap
for( int h=0; h<pbm->height; h++ ){
for ( int w=0; w<pbm->width; w++ ){
fprintf(outfile, "%d ", pbm->pixmap[h][w] );
}
fprintf(outfile, "\n"); //newline after each row
}
fclose( outfile );
}
void write_pgmfile( PGMImage *pgm, const char * filename ){
FILE * outfile;
if( (outfile = fopen( filename, "w" )) == NULL ) {
perror("fopen()");
exit( -1 );
}
//write pgm header
fprintf(outfile, "P2\n%d %d\n%d\n", pgm->width, pgm->height, pgm->max);
//write pgm pixmap
for( int h=0; h<pgm->height; h++ ){
for ( int w=0; w<pgm->width; w++ ){
fprintf(outfile, "%d ", pgm->pixmap[h][w] );
}
fprintf(outfile, "\n"); //newline after each row
}
fclose( outfile );
}