Ejercicio
Ancho y alto BMP, FileStream
Objetivo
Cree un programa de C# para mostrar el ancho y el alto de un archivo BMP mediante FileStream.
Recuerda la estructura de la cabecera:
File type (letters BM)
0-1
FileSize
2-5
Reserved
6-7
Reserved
8-9
Start of image data
10-13
Sizeofbitmapheader
14-17
Width (pixels)
18-21
Height (pixels)
22-25
Numberofplanes
26-27
Sizeofeachpoint
28-29
Compression(0=notcompressed)
30-33
Imagesize
34-37
Horizontal resolution
38-41
Verticalresolution
42-45
Sizeofcolortable
46-49
Importantcolorscounter
50-53
Código de Ejemplo
// Import the necessary namespaces for file handling
using System;
using System.IO;
class BMPDimensions
{
// Main method where the program starts
static void Main(string[] args)
{
// Prompt the user to enter the path of the BMP file
Console.WriteLine("Enter the path of the BMP file:");
// Get the file path from user input
string filePath = Console.ReadLine();
// Check if the file exists
if (File.Exists(filePath))
{
try
{
// Open the BMP file for reading in binary mode
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// Create a binary reader to read the BMP file data
using (BinaryReader reader = new BinaryReader(fs))
{
// Read the 'BM' file type (2 bytes) to confirm it's a BMP file
string fileType = new string(reader.ReadChars(2));
if (fileType != "BM")
{
Console.WriteLine("This is not a valid BMP file.");
return;
}
// Skip to the width and height data in the BMP header
reader.BaseStream.Seek(18, SeekOrigin.Begin);
// Read the width and height (4 bytes each)
int width = reader.ReadInt32();
int height = reader.ReadInt32();
// Display the width and height of the BMP image
Console.WriteLine("Width: " + width + " pixels");
Console.WriteLine("Height: " + height + " pixels");
}
}
}
catch (Exception ex) // Catch any errors that occur during reading
{
// Output an error message if an exception is thrown
Console.WriteLine("An error occurred: " + ex.Message);
}
}
else
{
// Inform the user if the specified file doesn't exist
Console.WriteLine("The specified file does not exist.");
}
}
}