Exercise
BMP width & height, FileStream
Objetive
Create a C# program to display the width and height of a BMP file using a FileStream.
Remember the structure of the BMP header:
File type (letters BM)
0-1
File Size
2-5
Reserved
6-7
Reserved
8-9
Start of image data
10-13
Size of bitmap header
14-17
Width (pixels)
18-21
Height (pixels)
22-25
Number of planes
26-27
Size of each point
28-29
Compression (0=not compressed)
30-33
Image size
34-37
Horizontal resolution
38-41
Vertical resolution
42-45
Size of color table
46-49
Important colors counter
50-53
Example Code
// Import the necessary namespaces for file handling
using System;
using System.IO;
class BMPDimensions
{
// Main method where the program starts
static void Main(string[] args)
{
// Prompt the user to enter the path of the BMP file
Console.WriteLine("Enter the path of the BMP file:");
// Get the file path from user input
string filePath = Console.ReadLine();
// Check if the file exists
if (File.Exists(filePath))
{
try
{
// Open the BMP file for reading in binary mode
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// Create a binary reader to read the BMP file data
using (BinaryReader reader = new BinaryReader(fs))
{
// Read the 'BM' file type (2 bytes) to confirm it's a BMP file
string fileType = new string(reader.ReadChars(2));
if (fileType != "BM")
{
Console.WriteLine("This is not a valid BMP file.");
return;
}
// Skip to the width and height data in the BMP header
reader.BaseStream.Seek(18, SeekOrigin.Begin);
// Read the width and height (4 bytes each)
int width = reader.ReadInt32();
int height = reader.ReadInt32();
// Display the width and height of the BMP image
Console.WriteLine("Width: " + width + " pixels");
Console.WriteLine("Height: " + height + " pixels");
}
}
}
catch (Exception ex) // Catch any errors that occur during reading
{
// Output an error message if an exception is thrown
Console.WriteLine("An error occurred: " + ex.Message);
}
}
else
{
// Inform the user if the specified file doesn't exist
Console.WriteLine("The specified file does not exist.");
}
}
}