画像の簡易入出力とテストプログラムを追加
[cuda.git] / libutils / ImageIO.h
1 /*
2         Copyright (C) 2012  fmaj7b5.info
3
4         This program is free software: you can redistribute it and/or modify
5         it under the terms of the GNU General Public License as published by
6         the Free Software Foundation, either version 2 of the License, or
7         (at your option) any later version.
8
9         This program is distributed in the hope that it will be useful,
10         but WITHOUT ANY WARRANTY; without even the implied warranty of
11         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12         GNU General Public License for more details.
13
14         You should have received a copy of the GNU General Public License
15         along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #ifndef FM7b5_IMAGE_IO_H
19 #define FM7b5_IMAGE_IO_H
20
21 #include <string>
22 #include <stdexcept>
23 #include <cstdint>
24
25 #include "Image.h"
26
27 namespace FM7b5
28 {
29         Image<std::uint8_t> loadPGM(const std::string& filename);
30
31         template <typename T>
32         void savePGM(const Image<T>& image, const std::string& filename);
33
34
35         /* implementation */
36         template <typename T>
37         void savePNM(const Image<T>& image, const std::string& filename)
38         {
39                 FILE* fp(nullptr);
40
41                 if (fopen_s(&fp, filename.c_str(), "wb") != 0) {
42                         throw std::runtime_error(__FUNCTION__ ": could not open a file.");
43                 }
44
45                 /* magic */
46                 switch(image.bpp()) {
47                 case 1:
48                         fprintf(fp, "P5\n");
49                         break;
50
51                 case 3:
52                         fprintf(fp, "P6\n");
53                         break;
54
55                 default:
56                         fclose(fp);
57                         throw std::runtime_error(__FUNCTION__ ": unknown format.");
58                         break;
59                 }
60
61                 /* width, height, depth */
62                 fprintf(fp, "%d %d\n%d\n", image.width(), image.height(), 255);
63
64                 /* binary data */
65                 for (size_t h = 0; h < image.height(); ++h) {
66                         const size_t width(image.width());
67
68                         size_t ret = fwrite(image.data() + image.stride() * h, image.bpp(), width, fp);
69                         if (ret != width) {
70                                 fclose(fp);
71                                 throw std::runtime_error(__FUNCTION__ ": could not write correctly.");
72                         }
73                 }
74         }
75 }
76
77 #endif /* FM7b5_IMAGE_IO_H */