I haven't been programming in C++ for a while, and now I have to write a simple thing, but it's driving me nuts.
I need to create a bitmap from a table of colors:
char image[200][200][3];
First coordinate is width, second height, third colors: RGB. How to do it?
Thanks for any help. Adam
I'm sure you've already checked http://en.wikipedia.org/wiki/BMP_file_format.
With that information in hand we can write a quick BMP with:
// setup header structs bmpfile_header and bmp_dib_v3_header before this (see wiki)
// * note for a windows bitmap you want a negative height if you're starting from the top *
// * otherwise the image data is expected to go from bottom to top *
FILE * fp = fopen ("file.bmp", "wb");
fwrite(bmpfile_header, sizeof(bmpfile_header), 1, fp);
fwrite(bmp_dib_v3_header, sizeof(bmp_dib_v3_header_t), 1, fp);
for (int i = 0; i < 200; i++) {
for (int j = 0; j < 200; j++) {
fwrite(&image[j][i][2], 1, 1, fp);
fwrite(&image[j][i][1], 1, 1, fp);
fwrite(&image[j][i][0], 1, 1, fp);
}
}
fclose(fp);
If setting up the headers is a problem let us know.
Edit: I forgot, BMP files expect BGR instead of RGB, I've updated the code (surprised nobody caught it).
It would be advisable to initialise the function as a simple 1 dimensional array.
ie (Where bytes is the number of bytes per pixel)
char image[width * height * bytes];
You can then access the relevant position in the array as follows
char byte1 = image[(x * 3) + (y * (width * bytes)) + 0];
char byte2 = image[(x * 3) + (y * (width * bytes)) + 1];
char byte3 = image[(x * 3) + (y * (width * bytes)) + 2];
I would first try to find out, how the BMP file format (that's what you mean by a bitmap, right?) is defined. Then I would convert the array to that format and print it to the file.
If that's an option, I would also consider trying to find an existing library for BMP files creation, and just use it.
Sorry if what I said is already obvious for you, but I don't know on which stage of the process you are stuck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With