-
Notifications
You must be signed in to change notification settings - Fork 1
/
ppm.h
106 lines (99 loc) · 2.25 KB
/
ppm.h
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
/*
Read and write Netpbm files
Copyright 2014 Ahmet Inan <[email protected]>
*/
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "image.h"
struct image *read_ppm(char *name)
{
FILE *file = fopen(name, "r");
if (!file) {
fprintf(stderr, "could not open \"%s\" file to read.\n", name);
return 0;
}
if ('P' != fgetc(file) || '6' != fgetc(file)) {
fprintf(stderr, "file \"%s\" not P6 image.\n", name);
fclose(file);
return 0;
}
int integer[3];
struct image *image = 0;
int c = fgetc(file);
if (EOF == c)
goto eof;
for (int i = 0; i < 3; i++) {
while ('#' == (c = fgetc(file)))
while ('\n' != (c = fgetc(file)))
if (EOF == c)
goto eof;
while ((c < '0') || ('9' < c))
if (EOF == (c = fgetc(file)))
goto eof;
char str[16];
for (int n = 0; n < 16; n++) {
if (('0' <= c) && (c <= '9') && n < 15) {
str[n] = c;
if (EOF == (c = fgetc(file)))
goto eof;
} else {
str[n] = 0;
break;
}
}
integer[i] = atoi(str);
}
if (!(integer[0] && integer[1] && integer[2])) {
fprintf(stderr, "could not read image file \"%s\".\n", name);
fclose(file);
return 0;
}
if (integer[2] != 255) {
fprintf(stderr, "cant read \"%s\", only 8 bit per channel SRGB supported at the moment.\n", name);
fclose(file);
return 0;
}
image = new_image(name, integer[0], integer[1]);
for (int i = 0; i < 3 * image->total; i++) {
int v = fgetc(file);
if (EOF == v)
goto eof;
image->buffer[i] = v;
}
fclose(file);
return image;
eof:
fprintf(stderr, "EOF while reading from \"%s\".\n", name);
fclose(file);
delete_image(image);
return 0;
}
int clamp(int x, int a, int b)
{
return x < a ? a : x > b ? b : x;
}
int write_ppm(struct image *image)
{
FILE *file = fopen(image->name, "w");
if (!file) {
fprintf(stderr, "could not open \"%s\" file to write.\n", image->name);
return 0;
}
if (!fprintf(file, "P6 %d %d 255\n", image->width, image->height)) {
fprintf(stderr, "could not write to file \"%s\".\n", image->name);
fclose(file);
return 0;
}
for (int i = 0; i < 3 * image->total; i++) {
if (EOF == fputc(clamp(image->buffer[i], 0, 255), file))
goto eof;
}
fclose(file);
return 1;
eof:
fprintf(stderr, "EOF while writing to \"%s\".\n", image->name);
fclose(file);
return 0;
}