I am having some troubles when generating a .bmp file, from the code below i expected it to come out in shades of red, but as you'll see from the included picture it becomes both blue and green instead. Any ideas why this is happening?
struct Pixel
{
unsigned char r;
unsigned char g;
unsigned char b;
};
The main function generates the vector that holds all the pixel data, the color depends on the height of the image.
int main()
{
std::vector<Pixel> ImageData;
unsigned int Width = 640;
unsigned int Height = 480;
for (unsigned int i = 0; i < Height; i++)
{
for (unsigned int j = 0; j < Width; j++)
{
Pixel temp;
temp.r = i % 255;
temp.g = 0;
temp.b = 0;
ImageData.push_back(temp);
}
}
WriteBitMap("raytracer.bmp", Width, Height, ImageData);
return 0;
}
bool WriteBitMap(std::string Filename, const unsigned int Width, const unsigned int Height, std::vector<Pixel> ImageData)
{
//Create fileformat headers
BitmapFileHeader fh;
BitmapInfoHeader ih;
fh.bmtype[0] = 'B';
fh.bmtype[1] = 'M';
fh.iFileSize = sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader) + (Width*Height * 3);
fh.iOffsetBits = sizeof(BitmapFileHeader) + sizeof(BitmapInfoHeader);
ih.iSizeHeader = 40;
ih.iWidth = Width;
ih.iHeight = Height;
ih.iPlanes = 1;
ih.iBitCount = 24;
ih.Compression = 0;
//Open file for writing
std::ofstream file;
file.open(Filename, std::ios::out);
file.write(reinterpret_cast<char*>(&fh), sizeof(BitmapFileHeader));
file.write(reinterpret_cast<char*>(&ih), sizeof(BitmapInfoHeader));
for (auto it = ImageData.begin(); it != ImageData.end(); ++it)
{
char red = it->r;
char green = 0;
char blue = 0;
file.write(&blue, sizeof(char));
file.write(&green, sizeof(char));
file.write(&red, sizeof(char));
}
file.close();
return false;
}
Edit:
See solution further down
File needed to be opened in binary mode.