Creating Bitmap Files from Raw Pixel Data in C++

This post describes a means of taking data in the form of raw pixels containing RGB values as well as the image height, width and the number of bits per pixel (24 in this case) and converting this into a bitmap (BMP) file.

In this this post I originally described how I needed a means of representing binary array values (inkjet printhead nozzles turned ON/OFF) as a set of colored ‘squares’ or pixels, so that nozzles switched ON/OFF could be represented by two different colours – black or white. The bitmap width was always going to be 128, while the bitmap length (“SizeValue”) was one of a set of discrete set of values in the range { 1000, 1250, 1251, 1350 }. For this example I did not have to worry about padding additional values

Since then I have made some improvements to the original code sample, specifically if the image data happens to be not DWORD-aligned, then a new data array is created and padded such that there will be enough bytes to reach the next DWORD.

The original task was to create a one-dimensional array of bytes representing pixel colour data from the two-dimensional adjacency matrix provided. Each pixel value was then set to black or white, depending on the matrix array value:

iii. Creates a file handler and writes the file, bitmap info and pixel data into it to create the new bitmap file representation:

Complete code listing

Here is the complete code listing to enable the user to:

1. Open an input bitmap file
2. Obtain the raw BYTE array, image height and image width from the input bitmap file
3. Create a new raw BYTE array, which will have space for additional padding if required
4. Save the new raw BYTE array to the new bitmap file.

The program works by first loading the bitmap data from the bitmap file provided eg shaunak.BMP:

The program extracts the raw data from this and puts it into the buffer, example output of this buffer data:

It then creates the new BYTE array with any additional padding, if necessary, and the BYTE data is saved as a new bitmap file, as mentioned previously. Here it is saved as “new_image.bmp” and as expected is a duplicate of the original bitmap file:

Here is another example of its usage. Instead of obtaining raw bitmap data from an existing bitmap file, I create my own bitmap, which in this case is a simple blue square. I then call

In your case you never actually need to add the padding since your width is 128 so the padding is 0.
However, if you try with other widths, there can be a shift in the byte array on each row, resulting in a degenerate picture.
This can however be fixed by adding the padding after c+=3; like this