Archived

This topic is now archived and is closed to further replies.

HappyDude

Writing Bitmap Files

Recommended Posts

Two questions about writing .bmp files. 1: In the BITMAPFILEHEADER structure, what is the bfOffBits member? I just have it always set to 54 because that''s the value I get from a .bmp file I''ve opened... but I have no idea what the value or the variable actually mean. 2: Why is it that when I''m writing the pixel information to the file after I''ve written the headers, if I use an "unsigned char buffer[2048][3]" my bitmap looks fine, but when I use an "unsigned char **buffer" and allocate the required amount of memory, it looks completly messed up? By the way, the bitmap image is 64x32 and 24-bit. Here''s the code I''m using... //This works unsigned char buffer[2048][3]; //*Code that fills up the buffer with my pixels* //*Code that opens up a bitmap file* //*Code that fills up the header files and writes them* fwrite(buffer,sizeof(char),2048*3,fptr);//note: fptr is my file pointer //This doesn''t work unsigned char **buffer buffer=new char*[2048]; for (int i=0;i<2048;i++) buffer=new char[3]; //*Code that fills up the buffer with my pixels* //*Code that opens up a bitmap file* //*Code that fills up the header files and writes them* fwrite(buffer,sizeof(char),2048*3,fptr);//note: fptr is my file pointer I can''t figure out why this happens . I need to get the second example to work, because I need to be able to dynamically allocate the memory for the buffer because the size of the image can change.

Share this post


Link to post
Share on other sites
About your second example:

You are allocating an array of 2048 pointers, each pointing to an array of 3 unsigned chars.

You should probably allocate your memory like this:

    
int number_of_pixels = 2048; // change this for other buffer sizes

unsigned char *buffer;
buffer = new char[number_of_pixels * 3];

just remember that each pixel takes up 3 elements in the array when you access it.

Alternatively (and prehaps a bit more intuitive), you can create an array of color-structs, like:

  
struct colour
{
unsigned char r, g, b;
};

int number_of_pixels = 2048; // change this for other buffer sizes

colour *buffer;
buffer = new color[number_of_pixels];

// then to change the green element of the 6th pixel yo do:

buffer[6].g = 45; // whatever


(btw, you should probably make sure that the colour-struct is packed to byte-boundaries, look up "#pragma pack" if you're using MSVC)

Edited by - Dactylos on October 13, 2001 12:42:13 AM

Share this post


Link to post
Share on other sites