Group
File Handling in C#
Objective
1. Open the BMP file and read the header to retrieve the position of the image data (start of image data).
2. Skip any irrelevant information, such as the color palette.
3. For each pixel in the image, check its color value.
4. If the color value is 255, display an 'X' in the console; otherwise, display a blank space.
5. The image will be 72 pixels wide and 24 pixels high, so ensure that the program handles these dimensions correctly.
Create a program to display a 72x24 BMP file on the console.
Example C# Exercise
Show C# Code
using System;
using System.IO;
class BMPDisplay
{
// Main method to execute the program
static void Main(string[] args)
{
// Check if the user has provided a file name as a command-line argument
if (args.Length == 0)
{
Console.WriteLine("Please provide a BMP file name as a command-line argument.");
return;
}
// Define the file path from the command-line argument
string filePath = args[0];
// Open the BMP file for reading in binary mode
using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{
// Read the BMP file header
reader.BaseStream.Seek(18, SeekOrigin.Begin); // Seek to the width/height part of the header
int width = reader.ReadInt32(); // Read image width
int height = reader.ReadInt32(); // Read image height
// Skip to the start of image data (offset is 54 + header size for color palette)
reader.BaseStream.Seek(10, SeekOrigin.Begin);
int imageDataOffset = reader.ReadInt32(); // Get the start of image data
// Jump to the image data
reader.BaseStream.Seek(imageDataOffset, SeekOrigin.Begin);
// Loop through each row of the image
for (int y = 0; y < height; y++)
{
// Loop through each pixel in the row
for (int x = 0; x < width; x++)
{
// Read the pixel color (1 byte for grayscale, as it's a 256-color image)
byte pixel = reader.ReadByte();
// If the color value is 255 (white), display "X", otherwise display a blank space
if (pixel == 255)
{
Console.Write("X");
}
else
{
Console.Write(" "); // Blank space for other colors
}
}
// Move to the next line after each row of pixels
Console.WriteLine();
}
}
// Notify the user that the operation is complete
Console.WriteLine("BMP file has been processed and displayed.");
}
}
Output
X X X X X X X X X X X X X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X X X
X X X X X X X X X X X X X X X X
... (continuation of 72 characters per line for 24 rows)