title: Read/Write SImple BMP Image C++
body: <p>I am trying to read simple BMP file and without performing any operations I am writing it back again to file.</p>
  
  <p>I don't know where the mistake is in reading the file or writing it back.
  I have added padding while reading as well as while writing</p>
  
  <p>-- File-Read --.</p>
  
  <pre><code>std::vector&lt;char&gt; tempImageData;
  /*tempImageData.resize(m_bmpInfo-&gt;imagesize);
  file.seekg(m_bmpHeader-&gt;dataoffset);
  file.read(&amp;tempImageData[0], m_bmpInfo-&gt;imagesize);
  file.close();*/
  tempImageData.resize(m_bmpInfo-&gt;imagesize);
  int padding = 0;
  while (((m_bmpInfo-&gt;width*3+padding) % 4) != 0 )
      padding++;
  for(unsigned int i = 0 ; i &lt; m_bmpInfo-&gt;height ; i++)
  {
      file.seekg(m_bmpHeader-&gt;dataoffset + i*(m_bmpInfo-&gt;width*3 + padding));
      file.read(&amp;tempImageData[i*m_bmpInfo-&gt;width*3], i*m_bmpInfo-&gt;width*3);
  }
  file.close();
  //bitmaps are stored as BGR -- lets convert to RGB
  assert(m_bmpInfo-&gt;imagesize % 3 == 0);
  
  for (auto i = tempImageData.begin(); i != tempImageData.end(); i+=3)
  {
      m_data_red.push_back(*(i+2));
      m_data_green.push_back(*(i+1));
      m_data_blue.push_back(*(i+0));
  }
  </code></pre>
  
  <p>-- write code</p>
  
  <pre><code>file.write(reinterpret_cast&lt;const char*&gt;(m_bmpHeader), sizeof(BITMAPFILEHEADER));
  file.write(reinterpret_cast&lt;const char*&gt;(m_bmpInfo), sizeof(BITMAPINFOHEADER));
  
  // this is wrong.. format asks for bgr.. we are putting all r, all g, all b
  std::vector&lt;char&gt; img;
  img.reserve(m_data_red.size() + m_data_green.size() + m_data_blue.size());
  
  for(unsigned int i = 0 ; i &lt; m_data_red.size() ; i++)
  {
      img.push_back(m_data_blue[i]);
      img.push_back(m_data_green[i]);
      img.push_back(m_data_red[i]);
  }
  
  char bmppad[3] = {0};
  
  for(unsigned int i = 0 ; i &lt; m_bmpInfo-&gt;height ; i++)
  {
      // maybe something is wrong
      file.write(reinterpret_cast&lt;const char*&gt;(&amp;img[i*m_bmpInfo-&gt;width*3]), m_bmpInfo-&gt;width * 3 * sizeof(unsigned char));
      file.write(bmppad, 1 * ((4-(m_bmpInfo-&gt;width*3)%4)%4) * sizeof(char));
  }
  
  file.close();
  </code></pre>
  
  <p>But the results are weird. </p>
  
  <pre><code>Output image------Input image
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/ykEW2.png" alt="enter image description here">
  <img src="https://i.stack.imgur.com/NdFKm.png" alt="Input Image"></p>