Advertisement
homer512

rgb

Apr 7th, 2014
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <fstream>
  2. // using std::ofstream, std::ifstream, std::streampos
  3.  
  4. void write(const char* fname, const SomeType& processedImage)
  5. {
  6.   std::ofstream file(fname);
  7.   file.exceptions(std::ofstream::badbit);
  8.  
  9.   const unsigned short cols = image.columns(), rows = image.rows();
  10.   file.write(reinterpret_cast<const char*>(&cols), sizeof(cols));
  11.  
  12.   for(int col = 0; col != cols; ++col) {
  13.     for(int row = 0; row != rows; ++row) {
  14.       const Magick::ColorRGB rgb = processedImage.pixelColor(col, row);
  15.       const unsigned char bytes[] = {
  16.     rgb.red() * 255, rgb.green() * 255, rgb.blue() * 255
  17.       };
  18.       file.write(reinterpret_cast<const char*>(bytes), sizeof(bytes));
  19.     }
  20.   }
  21. }
  22.  
  23. void read(const char* fname, SomeType& imageOutput)
  24. {
  25.   std::ifstream file(fname);
  26.   file.exceptions(std::ifstream::badbit | std::ifstream::failbit);
  27.  
  28.   unsigned short cols;
  29.   file.read(reinterpret_cast<char*>(&cols), sizeof(cols));
  30.   const std::streampos pos = file.tellg();
  31.   file.seekg(0, std::ifstream::end);
  32.   const std::streampos end = file.tellg();
  33.   const unsigned short rows = (end - pos) / (cols * 3);
  34.   file.seekg(pos, std::ifstream::beg);
  35.  
  36.   imageOutput.setCols(cols);
  37.   imageOutput.setRows(rows);
  38.  
  39.   for(int col = 0; col != cols; ++col) {
  40.     for(int row = 0; row != rows; ++row) {
  41.       unsigned char bytes[3];
  42.       file.read(reinterpret_cast<char*>(&bytes), sizeof(bytes));
  43.       const Magick::ColorRGB rgb(bytes[0] / 255., bytes[1] / 255., bytes[2] / 255.);
  44.       imageOutput.setPixelColor(col, row, rgb);
  45.     }
  46.   }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement