Ejercicio
Ancho y alto BMP, BinaryReader
Objetivo
Vuelva a crear un programa de C# para mostrar el ancho y el alto de un archivo BMP mediante un BinaryReader.
La estructura del encabezado de un archivo BMP es:
Tipo de archivo (letras BM)
0-1
Tamaño de archivo
2-5
Reservado
6-7
Reservado
8-9
Inicio de los datos de imagen
10-13
Sizeofbitmapheader
14-17
Ancho (píxeles)
18-21
Altura (píxeles)
22-25
Número de aviones
26-27
Tamañode cada punto
28-29
Compresión (0 = no comprimida)
30-33
Tamaño de imagen
34-37
Resolución horizontal
38-41
Resolución vertical
42-45
Tamañodecolorable
46-49
Importantcolorscounter
50-53
Código de Ejemplo
// Import the System namespace for basic functionality
using System;
// Import the IO namespace for file handling
using System.IO;
// Create the class to read BMP file header
class BMPReader
{
// Main method where the program starts
static void Main(string[] args)
{
// Ask the user for the BMP file path
Console.WriteLine("Enter the path of the BMP file:");
// Get the file path from the user
string filePath = Console.ReadLine();
// Start of try block to handle any file or reading errors
try
{
// Open the BMP file with BinaryReader to read the binary data
using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{
// Check if the first two bytes are 'BM' to validate it as a BMP file
if (reader.ReadByte() == 0x42 && reader.ReadByte() == 0x4D)
{
// Skip the file size and reserved bytes (2 to 9)
reader.BaseStream.Seek(8, SeekOrigin.Begin);
// Skip to the position where the width is stored (18-21)
int width = reader.ReadInt32();
// Skip to the position where the height is stored (22-25)
int height = reader.ReadInt32();
// Display the width and height of the BMP file
Console.WriteLine("Width: " + width + " pixels");
Console.WriteLine("Height: " + height + " pixels");
}
else
{
// If the file is not a valid BMP file, inform the user
Console.WriteLine("The file is not a valid BMP file.");
}
}
}
catch (Exception ex) // Catch any exceptions that may occur during file reading
{
// Print the exception message if an error occurs
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}