I do not know about jpg/jpeg, gif, or others, but I do know about BMP images.
The file header size is 14 bytes. The first two bytes are the header field, composed of two char
s (usually ‘B’, and then ‘M’). Then comes the total size of the BMP file (as a 4-byte integer), the next two fields are reserved and are both 2 bytes (so can both be set to 0), and finally, the last part of the file header is a 4-byte integer of the offset at which the pixel array will start.
After the file header comes the information header. There are various different ones in use, but among the most common is the BITMAPINFOHEADER
.
This header consists of: the header size in bytes - which is 40 (4 bytes), then the width of the pixel array in pixels (4 bytes), then the height of the pixel array in pixels (4 bytes), then the number of colour panes - usually 1 (2 bytes), then the bits per pixel - often 24 (2 bytes), and finally 6 more fields which are each 4 bytes large and can be set to 0 (will not go into detail to keep the answer short).
After this you can start writing the pixel array.
If you choose 24 bits per pixel, then each pixel will take 3 bytes of data, each byte representing an unsigned char
(from 0 to 255) corresponding to red, green or blue. BMP images use the BGR convention, so be sure to write the colour bytes in that order.
Finally, you will need to ensure that each row terminates at a 4-byte boundary. In other words, if the number of bytes in a row of the pixel array is not a multiple of 4, you will have to add in a corresponding amount of ‘padding’ bytes (usually just zeros) - either 1, 2 or 3 bytes.
And there, you’ve got yourself a BMP image!
If you would like any more details, I’d be happy to oblige.