-
Notifications
You must be signed in to change notification settings - Fork 1
/
readwriteppm.c
executable file
·120 lines (76 loc) · 3.03 KB
/
readwriteppm.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
#include "a4.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Read a .ppm image into a PPM_IMAGE
PPM_IMAGE *read_ppm(const char *file_name) {
// String to store the computed magic number
char magicNum[3];
int results;
// Open the file
FILE * readFile = fopen(file_name, "r");
// Read the magic number and make sure it is correct
results = fscanf(readFile, "%s\n", magicNum);
if (results == EOF) {
fprintf(stderr, "The image file is empty");
return NULL;
} else if (!strcmp(magicNum, "P3")) {
// If the magic number is correct
// Make an image object and allocate for it
PPM_IMAGE * readImage = malloc(sizeof(PPM_IMAGE));
// Read the width, height, and max colour value into the image
results = fscanf(readFile,
"%d %d %d",
&(readImage->width),
&(readImage->height),
&(readImage->max_color));
// Allocate an array of pixels for the image
readImage->data = (PIXEL *) malloc(readImage->width * readImage->height * sizeof(PIXEL));
// For each pixel
int i;
unsigned int r, g, b;
for (i = 0; i < readImage->width * readImage->height; i++) {
// Read the colour values as unsigned integers
results = fscanf(readFile, "%u %u %u", &r, &g, &b);
// Convert the read numbers into unsigned characters and put them into the pixel
readImage->data[i].r = (unsigned char)r;
readImage->data[i].g = (unsigned char)g;
readImage->data[i].b = (unsigned char)b;
}
// Close the file from reading
fclose(readFile);
// Return the created image
return readImage;
} else {
// The magic number does not match
// Spit out an error message
fprintf(stderr, "The file had an incorrect magic number: '%s'\n", magicNum);
// Close the file
fclose(readFile);
return NULL;
}
}
// Write a PPM_IMAGE to file as a .ppm
void write_ppm(const char *file_name, const PPM_IMAGE *image) {
FILE * writtenFile = fopen(file_name, "w");
// Write the magic number
fprintf(writtenFile, "P3\n");
// Write width, height, and max colour
fprintf(writtenFile, "%d %d\n%d\n", image->width, image->height, image->max_color);
int row, col;
// Used to point to the pixels when going through the list
PIXEL * pixelIterator = image->data;
for (row = 0; row < image->height; row++) {
for (col = 0; col < image->width; col++) {
// Print the data associated with the pixel into the file
fprintf(writtenFile, "%u %u %u\t",
(unsigned int)(pixelIterator->r),
(unsigned int)(pixelIterator->g),
(unsigned int)(pixelIterator->b));
pixelIterator++;
}
fprintf(writtenFile, "\n");
}
// Close the file
fclose(writtenFile);
}