Display BMP On Console V2 - C# Programming Exercise

In this exercise, you are asked to develop a program in C# that can display a 72x24 BMP file on the console. To do this, you must use the information contained in the BMP header, paying special attention to the "start of image data" field. This field indicates the position where the image pixel data begins, which is the crucial part you need to process. You can ignore the color palette information and instead represent the image on the console using characters: draw an "X" when the pixel color value is 255 (white), and a blank space when the value is different.

This exercise will help you understand how to handle binary data in a BMP file and how to extract and visually represent the pixels of an image on the console, which is an interesting challenge for working with graphics in a text environment.

Note: For testing purposes, you can create a test image in Paint for Windows by following the steps provided, creating a 72x24 pixel image with 256 colors, and saving it as a "256 color bitmap (BMP)".

 Category

File Management

 Exercise

Display BMP On Console V2

 Objective

Create a program to display a 72x24 BMP file on the console. You must use the information in the BMP header (refer to the exercise of Feb. 7th). Pay attention to the field named "start of image data". After that position, you will find the pixels of the image. You can ignore the information about the color palette and draw an "X" when the color is 255, and a blank space if the color is different.

Note: You can create a test image with the following steps on Paint for Windows: Open Paint, create a new image, change its properties in the File menu so that it is a color image, width 72, height 24, and save as "256 color bitmap (BMP)".

 Write Your C# Exercise

// Importing the System namespace to use its classes
using System; 

using System.IO; // Importing the IO namespace to handle file operations

class BmpViewer
{
    // The main method, where the program execution begins
    static void Main(string[] args)
    {
        // Check if a BMP file has been provided as a command-line argument
        if (args.Length < 1)
        {
            // Display an error message if no file name is provided
            Console.WriteLine("You must provide a BMP file as an argument.");
            return; // Exit the program if no file is provided
        }

        // Retrieve the file name from the command-line arguments
        string fileName = args[0];

        try
        {
            // Read the entire BMP file into a byte array
            byte[] bmpData = File.ReadAllBytes(fileName);

            // Check if the file starts with the "BM" signature, indicating a valid BMP file
            if (bmpData[0] != 'B' || bmpData[1] != 'M')
            {
                // Display an error message if the file is not a BMP file
                Console.WriteLine("The file is not a valid BMP file.");
                return; // Exit the program if the format is incorrect
            }

            // The starting position of the image data is located at byte 10 (4-byte offset)
            int startOfImageData = BitConverter.ToInt32(bmpData, 10);

            // Set the width and height of the BMP image
            int width = 72; // Fixed width as per the exercise requirement
            int height = 24; // Fixed height as per the exercise requirement

            // Iterate through each pixel in the BMP file
            for (int y = 0; y < height; y++)
            {
                // For each row, we need to read 72 pixels (3 bytes per pixel: Blue, Green, Red)
                for (int x = 0; x < width; x++)
                {
                    // Calculate the byte index for the current pixel
                    int pixelIndex = startOfImageData + (y * width + x) * 3;

                    // Extract the RGB values of the pixel (Blue, Green, Red)
                    byte blue = bmpData[pixelIndex];
                    byte green = bmpData[pixelIndex + 1];
                    byte red = bmpData[pixelIndex + 2];

                    // If the pixel color is white (255, 255, 255), display an "X"
                    if (red == 255 && green == 255 && blue == 255)
                    {
                        Console.Write("X");
                    }
                    else
                    {
                        // Otherwise, display a blank space
                        Console.Write(" ");
                    }
                }

                // After printing a row of pixels, move to the next line
                Console.WriteLine();
            }
        }
        catch (Exception ex)
        {
            // Display an error message if an exception occurs during file processing
            Console.WriteLine($"Error processing the file: {ex.Message}");
        }
    }
}

 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#.

  •  Writing to a text file

    In this exercise of C#, you need to create a program that asks the user for several sentences (until they just press Enter without typing anything) and stores those s...

  •  Appending to a text file

    In this exercise of C#, you need to create a program that asks the user for several sentences (until they just press Enter without typing anything) and stores those s...

  •  Display file contents

    In this exercise of C#, you need to create a program that displays all the contents of a text file on the screen. The file name will either be entered via the command...

  •  Extended TextToHTML (files)

    In this exercise of C#, you need to expand the TextToHtml class so that it can dump its result to a text file. You should create a ToFile method that ta...

  •  Logger

    In this exercise of C#, you need to create a Logger class with a static Write method, which will append a certain text to a log file. The method should ...

  •  More

    In this exercise of C#, you need to create a program that behaves like the Unix "more" command. The program should display the contents of a text file and prom...