forked from jcbritobr/sray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ppmimage.cpp
executable file
·53 lines (44 loc) · 1.42 KB
/
ppmimage.cpp
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
#include "ppmimage.hpp"
//TODO:: write tests -- this code compiles :-)
constexpr auto P3MARKER = "P3";
constexpr auto PPMNL = '\n';
constexpr auto PPMSPACE = ' ';
constexpr auto PPMMAGIC = 255;
std::ostream &operator <<(std::ostream &stream, const PPMImage &image)
{
stream << P3MARKER << PPMNL << image.width << PPMSPACE << image.height << PPMNL << PPMMAGIC << PPMNL;
if( !stream ) return stream;
for ( const auto& color: image.data ) {
stream << color.r() << PPMSPACE << color.g() << PPMSPACE << color.b() << PPMNL;
if( !stream ) return stream;
}
return stream;
}
std::istream &operator >>(std::istream &stream, PPMImage &image)
{
if( !stream ) return stream;
std::string p3;
stream >> p3;
if( !stream ) return stream;
if( p3 != P3MARKER ) {
stream.setstate(std::ios_base::failbit);
return stream;
}
size_t width, height, magic;
stream >> width >> height >> magic;
if( !stream ) return stream;
if( magic != PPMMAGIC ) {
stream.setstate(std::ios_base::failbit);
return stream;
}
std::vector<Color> data;
data.reserve(width*height); // avoid reallocations and copies
for( auto count = width*height; count --> 0; ) {
float r, g, b;
stream >> r >> g >> b;
if( !stream ) return stream;
data.emplace_back(r, g, b);
}
image = PPMImage { width, height, data };
return stream;
}