Ejercicio
Mostrar BMP en la consola V2
Objetivo
Cree un programa para mostrar un archivo BMP de 72x24 en la consola.
Debe usar la información en el encabezado (ver el ejercicio del 7 de febrero). Preste atención al campo llamado "inicio de los datos de imagen". Después de esa posición, encontrará los píxeles de la imagen (puede ignorar la información sobre la paleta de colores y dibujar una "X" cuando el color es 255, y un espacio en blanco si el color es diferente).
Nota: puede crear una imagen de prueba, con los siguientes pasos (en Paint para Windows): Abra Paint, cree una nueva imagen, cambie sus propiedades en el menú Archivo para que sea una imagen en color, ancho 72, altura 24, guardar como "mapa de bits de 256 colores (BMP)".
Código de Ejemplo
// 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}");
}
}
}