The example code I’ve seen for this seems to use standard C file output functions, but I’d like to make it in C++.
I tried using fsteam functions to do it, but no data is written to the .bmp file at all.
So far, I have tried the standard <<, put, and write, and none of these work. If I open it up with a hex editor, the file is still empty.
It’s odd, since the input functions work fine.
Here’s a piece of the code I used to test to see if it was working:
output.open("WHITE.bmp");
output.put('B'); // this doesn't seem to work, the file is empty when I open it in a hex editor.
output.put('M');
And the rest of the code:
#include <iostream>
#include <fstream>
using namespace std;
typedef unsigned char byte;
typedef unsigned short dbyte;
struct BMPINFO
{
int width;
int height;
};
int main()
{
ifstream sourcefile;
ofstream output;
int threshold = 150;
sourcefile.open("RED.bmp");
if(sourcefile.fail())
{
cout << "Could not open RED.bmp" << endl;
return 1;
}
if(sourcefile.get() == 'B')
{
if(sourcefile.get() == 'M')
{
cout << "RED.bmp is a valid .bmp file" << endl;
}
}
else
{
cout << "RED.bmp is not a valid .bmp file" << endl;
return 1;
}
BMPINFO image;
// seeks to bitmap width, this file is little end in.
sourcefile.seekg (0x12, ios::beg);
unsigned int i = (unsigned)sourcefile.get();
i += (unsigned)sourcefile.get() << 8;
image.width = i;
cout << "The width of the image is: " << image.width << endl;
sourcefile.seekg (0x16, ios::beg);
i = sourcefile.get();
i += (unsigned)sourcefile.get() << 8;
image.height = i;
cout << "The height of the image is: " << image.height << endl;
int loc_pixels;
sourcefile.seekg (0x0A, ios::beg);
loc_pixels = sourcefile.get();
cout << "Location of pixel array is: " << loc_pixels << endl;
output.open("WHITE.bmp");
output.put('B'); // this doesn't seem to work, the file is empty when I open it in a hex editor.
output.put('M');
if(output.bad())
{
cout << "the attempt to output didn't work" << endl;
return 1;
}
sourcefile.seekg(loc_pixels, ios::beg);
char data[30000];
output.close();
return 0;
}
Is there a special function I should be using to output to this .bmp file?
EDIT – added more code, though most of it doesn’t have to do with file output
You have a buffer overflow bug in this code:
You are reading in
image.height*image.widthbytes, and trying to fit them into30000bytes. You should structure your code so that those two numbers are related.Try this: