- Course
- Binary Files
- Read dimensions of BMP image
Read dimensions of BMP image
Last updated:
8/23/2020
⁃
Difficulty:
Intermediate
Create a program in C# to read the dimensions of an image in Windows bitmap format. You should first check that it is a valid .bmp image, reviewing the header data 'BM'. If it is a valid .bmp image then it obtained its dimensions (width x height) and display them on the screen.
It is a format of the Windows operating system. You can save images up to 24 bits (16.7 million colors).
The header of a BMP image is as follows:
Description | Bytes |
Type (BM) | 0-1 |
Size | 2-5 |
Reserved | 6-9 |
Start of image data | 10-13 |
Bitmap size | 14-17 |
Width (pixels) | 18-21 |
High (pixels) | 22-25 |
Number of plans | 26-27 |
Size of each point | 28-29 |
Compression | 30-33 |
Image size | 34-37 |
Horizontal resolution | 38-41 |
Vertical resolution | 42-45 |
Table color size | 46-49 |
Color counter | 50-53 |
Input
Output
48x48
Solution
using System;
using System.IO;
public class ReadDimensionsBmpImage
{
public static void Main(string[] args)
{
string fileName = "logo.bmp";
int size = 54, width, height;
byte[] data = new byte[size];
using (FileStream file = File.OpenRead(fileName))
{
file.Read(data, 0, size);
}
if (data[0] != 'B' || data[1] != 'M')
{
return; // Not a BMP file
}
width = data[18] + (data[19] * 256) +
(data[20] * 256 * 256) +
(data[21] * 256 * 256 * 256);
height = data[22] + (data[23] * 256) +
(data[24] * 256 * 256) +
(data[25] * 256 * 256 * 256);
Console.WriteLine("{0}x{1}", width, height);
}
}