/* Copyright (C) 2012 fmaj7b5.info This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #ifndef FM7b5_IMAGE_IO_H #define FM7b5_IMAGE_IO_H #include #include #include #include "Image.h" namespace FM7b5 { Image loadPGM(const std::string& filename); template void savePGM(const Image& image, const std::string& filename); /* implementation */ template void savePNM(const Image& image, const std::string& filename) { FILE* fp(nullptr); if (fopen_s(&fp, filename.c_str(), "wb") != 0) { throw std::runtime_error(__FUNCTION__ ": could not open a file."); } /* magic */ switch(image.bpp()) { case 1: fprintf(fp, "P5\n"); break; case 3: fprintf(fp, "P6\n"); break; default: fclose(fp); throw std::runtime_error(__FUNCTION__ ": unknown format."); break; } /* width, height, depth */ fprintf(fp, "%d %d\n%d\n", image.width(), image.height(), 255); /* binary data */ for (size_t h = 0; h < image.height(); ++h) { const size_t width(image.width()); size_t ret = fwrite(image.data() + image.stride() * h, image.bpp(), width, fp); if (ret != width) { fclose(fp); throw std::runtime_error(__FUNCTION__ ": could not write correctly."); } } } } #endif /* FM7b5_IMAGE_IO_H */