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
C# Exercise Example
// 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}");
}
}
}