Exercise
BMP width and height, BinaryReader
Objetive
Create a C# program to display the width and height of a BMP file using a BinaryReader.
The structure of the header of a BMP file is:
File type (letters BM) at positions 0-1.
File size at positions 2-5.
Reserved at positions 6-7.
Reserved at positions 8-9.
Start of image data at positions 10-13.
Size of bitmap header at positions 14-17.
Width (pixels) at positions 18-21.
Height (pixels) at positions 22-25.
Number of planes at positions 26-27.
Size of each point at positions 28-29.
Compression (0=not compressed) at positions 30-33.
Image size at positions 34-37.
Horizontal resolution at positions 38-41.
Vertical resolution at positions 42-45.
Size of color table at positions 46-49.
Example Code
using System;
using System.IO;
class BMPReader
{
static void Main(string[] args)
{
Console.WriteLine("Enter the path of the BMP file:");
string filePath = Console.ReadLine();
try
{
using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{
if (reader.ReadByte() == 0x42 && reader.ReadByte() == 0x4D)
{
reader.BaseStream.Seek(8, SeekOrigin.Begin);
int width = reader.ReadInt32();
int height = reader.ReadInt32();
Console.WriteLine("Width: " + width + " pixels");
Console.WriteLine("Height: " + height + " pixels");
}
else
{
Console.WriteLine("The file is not a valid BMP file.");
}
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}