-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPNM.c
executable file
·122 lines (96 loc) · 2.34 KB
/
PNM.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
117
118
119
120
121
122
/* ------------------------------------------------------------------------- *
* Implementation of the PNM interface
*
* Partly adapted from http://stackoverflow.com/a/2699908
* ------------------------------------------------------------------------- */
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <stdbool.h>
#include "PNM.h"
// Methods
PNMImage* createPNM(size_t width, size_t height) {
PNMImage* image = (PNMImage*) malloc(sizeof(PNMImage));
if (!image) {
return NULL;
}
image->width = width;
image->height = height;
image->data = (PNMPixel*) malloc(width * height * sizeof(PNMPixel));
if (!image->data) {
free(image);
return NULL;
}
return image;
}
void freePNM(PNMImage* image) {
if (image) {
free(image->data);
free(image);
}
}
PNMImage* readPNM(const char* filename){
char buffer[16];
int c;
// Open PNM file for reading
FILE* fp = fopen(filename, "rb");
if (!fp) {
return NULL;
}
// Read image format
if (!fgets(buffer, sizeof(buffer), fp)) {
return NULL;
}
if (buffer[0] != 'P' || buffer[1] != '6') {
return NULL;
}
// Check for comments
c = getc(fp);
while (c == '#') {
while (getc(fp) != '\n');
c = getc(fp);
}
ungetc(c, fp);
// Read image size
size_t width;
size_t height;
if (fscanf(fp, "%zu %zu", &width, &height) != 2) {
return NULL;
}
// Read RGB depth
if (fscanf(fp, "%d", &c) != 1) {
return NULL;
}
if (c != 255) {
return NULL;
}
while (fgetc(fp) != '\n') ;
// Allocate memory
PNMImage* image = createPNM(width, height);
if (!image) {
return NULL;
}
// Read pixels
if (fread(image->data, 3 * image->width,
image->height, fp) != image->height) {
freePNM(image);
return NULL;
}
fclose(fp);
return image;
}
int writePNM(const char* filename, const PNMImage* image){
// Open file
FILE* fp;
fp = fopen(filename, "wb");
if (!fp) {
return -1;
}
// Write content
fprintf(fp, "P6\n");
fprintf(fp, "%zu %zu\n",image->width, image->height);
fprintf(fp, "255\n");
fwrite(image->data, 3 * image->width, image->height, fp);
fclose(fp);
return 0;
}