summaryrefslogtreecommitdiff
path: root/libraries/daguerre/ppm.cpp
blob: e909503a44d6d826e0da2d2ac79bc7b741e8b922 (plain) (blame)
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
#include <daguerre/image.hpp>
#include <cctype>

namespace daguerre {

  static unsigned read_int(std::FILE *from) {
    unsigned out = 0;
    int ch;
    do
      ch = std::fgetc(from);
    while (std::isspace(ch));
    while (true) {
      if (ch == EOF)
        return out;
      if (ch < '0' || ch > '9') {
        std::ungetc(ch, from);
        return out;
      }
      out = out * 10 + (ch - '0');
      ch = std::fgetc(from);
    }
  }

  bool try_load_ppm(std::FILE *from, image<color24> &into) {

    if (std::fgetc(from) != 'P' || std::fgetc(from) != '6' ||
        std::fgetc(from) != '\n')
      return false;

    unsigned width = read_int(from);
    unsigned height = read_int(from);
    unsigned max = read_int(from);
    std::fgetc(from);//newline

    if (max != 255)
      return false;

    into = image<color24>(width, height);
    color24 *buffer = into.get_buffer();

    for (unsigned y = 0; y < height; ++y)
      for (unsigned x = 0; x < width; ++x) {
        buffer[y * width + x].r = std::fgetc(from);
        buffer[y * width + x].g = std::fgetc(from);
        buffer[y * width + x].b = std::fgetc(from);
      }

    return true;

  }

}