BMP Tutorial
BMP Tutorial
FIT-HCMUS
Contents
5 References 7
1
Programming Techniques — 2021 Knowledge Engineering Department
BMP files are commonly used for storing 2D digital images both monochrome and color. The
defautl BMP file is not a compressed image, has a fairly simple structure, is easier to read and edit
than other image formats.
This tutorial will focus on a 24-bit BMP file (with RGB color).
• File header: Contains information about the size of the file and the offset of the pixel data.
• Info header (DIB header): Contains overview information about the image such as width,
height, size per pixel (number of colors),...
2. Color table: not important when reading or writing so it will not be covered in this tutorial.
3. Pixel data: Also known as bitmap data, pixel array; contains the RGB color information of the
pixels.
Programming on Windows operating systems, we are supported with a full struct to read the
bitmap header data. We need to include the Windows.h library for support.
Page 2 / 7
Programming Techniques — 2021 Knowledge Engineering Department
The BMP file stores order color according to the Little Endian rule. That means instead of saving
according to Red → Green → Blue, BMP stores to Blue → Green → Red.
There will be padding on each row in the BMP image when the total data per row is
not divisible by 4. Padding bytes (not necessarily 0) must be appended to the end of the rows in
order to bring up the length of the rows to a multiple of four bytes [1].
2.2 An Example
Page 3 / 7
Programming Techniques — 2021 Knowledge Engineering Department
BMP Header
0 2 42 4D ”BM” ID field
DIB Header
Pixel Array
Page 4 / 7
Programming Techniques — 2021 Knowledge Engineering Department
9 struct BitmapImage
10 {
11 BITMAPFILEHEADER fileHeader; // #include <Windows.h>
12 BITMAPINFOHEADER infoHeader; // #include <Windows.h>
13
Page 5 / 7
Programming Techniques — 2021 Knowledge Engineering Department
This tutorial provides only program framework that helps you to read pixel array without imple-
menting.
1 BitmapImage bmpImage;
2
14 // Memory allocation for Pixel Array (2d array with the number of rows is height, the number of columns is
width.
15
22 // Loop from (height - 1) to 0 (row by row from the bottom to the top of the image):
23 // Read each rows of image into Pixel Array using:
24 fread(bmpImage.data[i], 3, width, fileName);
25
6 rewind(f);
7
8 // Writing header
9 retCode = fwrite(&bmpImage.fileHeader, sizeof(BITMAPFILEHEADER), 1, f);
10 retCode = fwrite(&bmpImage.infoHeader, sizeof(BITMAPINFOHEADER), 1, f);
11
12
Page 6 / 7
Programming Techniques — 2021 Knowledge Engineering Department
17
25 // Padding
26 if (bmpImage.padding != 0)
27 fwrite(tmp, 1, bmpImage.padding, f);
28 }
29 }
5 References
References
[1] Bitmap file format, https://en.wikipedia.org/wiki/BMP_file_format
[2] “DIBs and Their Uses”, Microsoft Help and Support, Retrieved 2015-05-14.
—— END ——
Page 7 / 7