Ancho y alto BMP, BinaryReader Aprende programación con ejercicios C# Sharp

Lección:

Administración de Archivos


Ejercicio:

Ancho y alto BMP, BinaryReader 60


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:

using System;
using System.IO;
public class BmpHeightWidth
{
    public static void Main()
    {
        BinaryReader myFile;
        byte b1, b2;
        int width, height;

        myFile = new BinaryReader(
            File.Open("example.bmp", FileMode.Open));
        b1 = myFile.ReadByte();
        b2 = myFile.ReadByte();

        if ((b1 == 0x42) && (b2 == 0x4D))
        {
            Console.WriteLine("It seems to be a BMP file");
            myFile.BaseStream.Seek(18, SeekOrigin.Begin);
            width = myFile.ReadInt32();
            height = myFile.ReadInt32();
            Console.WriteLine("Width: {0} pixels", width);
            Console.WriteLine("Height: {0} pixels", height);
        }
        else
            Console.WriteLine("It DOES NOT seem to be a BMP file");

        myFile.Close();
    }
}