Display BMP File Width and Height using BinaryReader in C#

This program is designed to read a BMP (Bitmap) image file and display its width and height. The BMP file format has a specific header structure, which contains important information about the image, such as its size, resolution, and dimensions. Using a BinaryReader, the program will access the binary content of the BMP file and extract the width and height values from the header.

The program works by opening the BMP file and reading the binary data at the specific byte offsets that correspond to the width and height. The program will then output these values to the user, providing the dimensions of the BMP image.



Group

File Handling in C#

Objective

1. The program will prompt the user for the BMP file name.
2. It will open the BMP file in binary mode using BinaryReader.
3. The program will read the specific bytes that correspond to the width and height of the image.
4. It will display the width and height of the image in pixels.
5. If the file is not found or is not a valid BMP file, the program will handle errors appropriately.

Create a C# program to display the width and height of a BMP file using a BinaryReader.

Example C# Exercise

 Copy C# Code
using System;
using System.IO;

class BMPDimensions
{
    // Main method that runs the program
    static void Main(string[] args)
    {
        // Ask the user for the name of the BMP file
        Console.WriteLine("Please enter the name of the BMP file:");

        // Read the name of the BMP file from the user
        string fileName = Console.ReadLine();

        try
        {
            // Open the file in binary mode using BinaryReader
            using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
                // Check if the file starts with "BM" (this indicates it's a BMP file)
                reader.BaseStream.Seek(0, SeekOrigin.Begin); // Move to the start of the file
                byte[] fileType = reader.ReadBytes(2); // Read the first two bytes

                // If the file type is not "BM", it's not a valid BMP file
                if (fileType[0] != 0x42 || fileType[1] != 0x4D)
                {
                    Console.WriteLine("This is not a valid BMP file.");
                    return;
                }

                // Read the width (bytes 18-21)
                reader.BaseStream.Seek(18, SeekOrigin.Begin);
                int width = reader.ReadInt32(); // Read the width value

                // Read the height (bytes 22-25)
                reader.BaseStream.Seek(22, SeekOrigin.Begin);
                int height = reader.ReadInt32(); // Read the height value

                // Display the width and height of the BMP image
                Console.WriteLine($"Width: {width} pixels");
                Console.WriteLine($"Height: {height} pixels");
            }
        }
        catch (FileNotFoundException)
        {
            // Handle file not found error
            Console.WriteLine("Error: The specified BMP file could not be found.");
        }
        catch (Exception ex)
        {
            // Handle other unexpected errors
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

 Output

//If the user enters image.bmp, and the file contains the following data at the relevant positions:
Width: 800 pixels (position 18-21)
Height: 600 pixels (position 22-25)

//The output would be:
Please enter the name of the BMP file:
image.bmp
Width: 800 pixels
Height: 600 pixels

Share this C# Exercise

More C# Practice Exercises of File Handling in C#

Explore our set of C# Practice 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 Text to HTML Converter in C#

    This program is a "Text to HTML Converter" that reads the contents of a source text file and converts it into an HTML file. The program will take the text file and process its cont...

  • File Inverter Using FileStream in C#

    This program takes a file and creates a new file where the bytes are inverted. The program reads the contents of the original file using a FileStream, then writes these contents to...

  • Display Width and Height of a BMP File Using FileStream in C#

    This program reads the header of a BMP (Bitmap) file and extracts the width and height of the image using FileStream. It uses the structure of the BMP header, where the width and h...

  • Copy Source File to Destination File Using FileStream in C#

    This program copies a source file to a destination file using FileStream in C#. The file is read and written in blocks of 512 KB at a time to handle large files efficiently. The pr...

  • Tag Reader for Audio Files in C#

    This program reads and extracts the ID3 version 1 tags from an audio file, specifically the last 128 bytes of the file, which contain metadata information such as the title, artist...

  • Simple C to C# Converter

    This program is designed to convert simple C programs into C# code. It takes a C program as input and translates it into a corresponding C# program that compiles and runs correctly...