| 1 | #include "cvd/internal/io/bmp.h" |
| 2 | #include "cvd/internal/load_and_save.h" |
| 3 | #include <vector> |
| 4 | using namespace std; |
| 5 | using namespace CVD; |
| 6 | |
| 7 | namespace CVD |
| 8 | { |
| 9 | namespace BMP |
| 10 | { |
| 11 | |
| 12 | void writeBMPHeader(unsigned int width, unsigned int height, unsigned int channels, std::ostream& out); |
| 13 | |
| 14 | class WritePimpl |
| 15 | { |
| 16 | public: |
| 17 | WritePimpl(ostream& o_, ImageRef sz, const string& t) |
| 18 | : o(o_) |
| 19 | , size(sz) |
| 20 | { |
| 21 | int ch; |
| 22 | |
| 23 | if(t == "unsigned char") |
| 24 | ch = 1; |
| 25 | else if(t == "CVD::Rgb<unsigned char>") |
| 26 | { |
| 27 | ch = 3; |
| 28 | int l = size.x * 3; |
| 29 | if(l % 4 != 0) |
| 30 | l = (l / 4 + 1) * 4; |
| 31 | buf.resize(l); |
| 32 | } |
| 33 | else |
| 34 | throw Exceptions::Image_IO::UnsupportedImageSubType("BMP", t); |
| 35 | |
| 36 | writeBMPHeader(size.x, size.y, ch, o); |
| 37 | |
| 38 | pad = ((ch * size.x) % 4) ? (4 - ((ch * size.x) % 4)) : 0; |
| 39 | } |
| 40 | |
| 41 | void write_raw_pixel_line(const byte* r) |
| 42 | { |
| 43 | char zeros[] = { 0, 0, 0, 0 }; |
| 44 | o.write((const char*)r, size.x); |
| 45 | o.write(zeros, pad); |
| 46 | } |
| 47 | |
| 48 | void write_raw_pixel_line(const Rgb<byte>* r) |
| 49 | { |
| 50 | //Transform to BGR |
| 51 | for(int i = 0; i < size.x; i++) |
| 52 | { |
| 53 | buf[i * 3 + 0] = r[i].blue; |
| 54 | buf[i * 3 + 1] = r[i].green; |
| 55 | buf[i * 3 + 2] = r[i].red; |
| 56 | } |
| 57 | o.write(&buf[0], buf.size()); |
| 58 | } |
| 59 | |
| 60 | private: |
| 61 | ostream& o; |
| 62 | ImageRef size; |
| 63 | int pad; |
| 64 | vector<char> buf; |
| 65 | }; |
| 66 | |
| 67 | Writer::Writer(std::ostream& o, ImageRef size, const std::string& type, const std::map<std::string, Parameter<>>&) |
| 68 | : t(new WritePimpl(o, size, type)) |
| 69 | { |
| 70 | } |
| 71 | |
| 72 | Writer::~Writer() |
| 73 | { |
| 74 | } |
| 75 | |
| 76 | void Writer::write_raw_pixel_line(const byte* l) |
| 77 | { |
| 78 | t->write_raw_pixel_line(l); |
| 79 | } |
| 80 | void Writer::write_raw_pixel_line(const Rgb<byte>* l) |
| 81 | { |
| 82 | t->write_raw_pixel_line(l); |
| 83 | } |
| 84 | |
| 85 | } |
| 86 | } |