BMP Width & Height, Filestream - C# Programming Exercise

This C# exercise involves creating a program that reads a BMP file using a FileStream and displays its width and height. The BMP format has a specific header structure that contains several fields with information about the image, such as the file type, file size, dimensions (width and height), and other technical details. In this exercise, you will learn how to work with binary files and read the header structures of a BMP file to extract important information.

The program should use a FileStream to open the BMP file and extract the data from specific positions within the file header. In particular, it should read positions 18-21 to get the width of the image (in pixels) and positions 22-25 to get the height of the image. This information is crucial to correctly display the image dimensions.

In addition to the dimensions, this exercise will help you become familiar with other aspects of the BMP format, such as image compression, horizontal and vertical resolution, and color table size. This exercise is ideal for learning how to handle binary files and retrieve relevant information from image files in C#, which can be useful in image processing applications or for displaying graphic files.

 Category

File Management

 Exercise

BMP Width & Height, Filestream

 Objective

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

 Write Your C# Exercise

// 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.");
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  File copier

    This C# exercise involves creating a program that copies a source file to a destination file using a FileStream and a block size of 512 KB. The program should ...

  •  MP3 reader

    This C# exercise is about the ID3 specifications, which apply to any file or audiovisual container, but are primarily used with audio containers. There are three comp...

  •  C to C# converter

    This exercise consists of creating a program that converts simple C programs, such as the following one, into C#, ensuring that the resulting program compiles ...

  •  File splitter

    This exercise involves creating a program that splits a file (of any kind) into pieces of a certain size. The program should receive the file name and the desired size of th...

  •  Encrypt a BMP file

    This exercise involves creating a program to encrypt and decrypt a BMP image file by changing the "BM" mark in the first two bytes to "MB" and vice versa. The program should...

  •  CSV converter

    This exercise involves creating a program that reads a CSV file with four data blocks (three text fields and one numeric) separated by commas, and generates a text file wher...