Cómo: Leer metadatos de imagen

Actualización: noviembre 2007

Algunos archivos de imagen contienen metadatos que se pueden leer para determinar ciertas características de la imagen. Por ejemplo, una fotografía digital quizás contenga metadatos que se pueden leer para determinar la marca y modelo de la cámara empleada para tomar la imagen. GDI+ permite leer los metadatos existentes y escribir metadatos nuevos en archivos de imagen.

GDI+ almacena un metadato en un objeto PropertyItem. La propiedad PropertyItems de un objeto Image se puede leer para recuperar todos los metadatos de un archivo. La propiedad PropertyItems devuelve una matriz de objetos PropertyItem.

Los objetos PropertyItem constan de las cuatro propiedades siguientes: Id, Value, Len y Type.

Id

Etiqueta que identifica el elemento de metadato. En la siguiente tabla se muestran algunos de los valores que pueden asignarse a Id.

Valor hexadecimal

Descripción

0x0320

0x010F

0x0110

0x9003

0x829A

0x5090

0x5091

Título de la imagen

Fabricante del equipo

Modelo del equipo

ExifDTOriginal

Tiempo de exposición en Exif

Tabla de luminancia

Tabla de cromaticidad

Valor

Matriz de valores. La propiedad Type determina el formato de los valores.

Len

La longitud (en bytes) de una matriz de valores indicada por la propiedad Value.

Tipo

El tipo de datos de los valores contenidos en la matriz indicada por la propiedad Value. La siguiente tabla muestra los formatos indicados por los valores de la propiedad Type.

Valor numérico

Descripción

1

Byte

2

Matriz de objetos Byte codificada en ASCII

3

Entero de 16 bits

4

Entero de 32 bits

5

Matriz de dos objetos Byte que representa un número racional

6

No se utiliza

7

No definido

8

No se utiliza

9

SLong

10

SRational

Ejemplo

Descripción

En el ejemplo de código siguiente se leen y muestran los siete metadatos del archivo FakePhoto.jpg. El segundo elemento de la propiedad (índice 1) de la lista tiene Id 0x010F (fabricante del equipo) y Type 2 (matriz de bytes codificada en ASCII). El ejemplo de código muestra el valor de ese elemento de propiedad.

El código produce un resultado similar al siguiente:

Property Item 0

id: 0x320

type: 2

length: 16 bytes

Property Item 1

id: 0x10f

type: 2

length: 17 bytes

Property Item 2

id: 0x110

type: 2

length: 7 bytes

Property Item 3

id: 0x9003

type: 2

length: 20 bytes

Property Item 4

id: 0x829a

type: 5

length: 8 bytes

Property Item 5

id: 0x5090

type: 3

length: 128 bytes

Property Item 6

id: 0x5091

type: 3

length: 128 bytes

The equipment make is Northwind Camera.

Código

'Create an Image object. 
Dim image As Bitmap = New Bitmap("c:\FakePhoto.jpg")

'Get the PropertyItems property from image.
Dim propItems As PropertyItem() = image.PropertyItems

'Set up the display.
Dim font As New Font("Arial", 12)
Dim blackBrush As New SolidBrush(Color.Black)
Dim X As Integer = 0
Dim Y As Integer = 0

'For each PropertyItem in the array, display the ID, type, and length.
Dim count As Integer = 0
Dim propItem As PropertyItem
For Each propItem In propItems
    e.Graphics.DrawString( _
       "Property Item " & count.ToString(), _
       font, _
       blackBrush, _
       X, Y)

    Y += font.Height

    e.Graphics.DrawString( _
       "   iD: 0x" & propItem.Id.ToString("x"), _
       font, _
       blackBrush, _
       X, Y)

    Y += font.Height

    e.Graphics.DrawString( _
       "   type: " & propItem.Type.ToString(), _
       font, _
       blackBrush, _
       X, Y)

    Y += font.Height

    e.Graphics.DrawString( _
       "   length: " & propItem.Len.ToString() & " bytes", _
       font, _
       blackBrush, _
       X, Y)

    Y += font.Height

    count += 1
Next propItem
'Convert the value of the second property to a string, and display it.
Dim encoding As New System.Text.ASCIIEncoding()
Dim manufacturer As String = encoding.GetString(propItems(1).Value)

e.Graphics.DrawString( _
   "The equipment make is " & manufacturer & ".", _
   font, _
   blackBrush, _
   X, Y)

// Create an Image object. 
Image image = new Bitmap(@"c:\FakePhoto.jpg");

// Get the PropertyItems property from image.
PropertyItem[] propItems = image.PropertyItems;

// Set up the display.
Font font = new Font("Arial", 12);
SolidBrush blackBrush = new SolidBrush(Color.Black);
int X = 0;
int Y = 0;

// For each PropertyItem in the array, display the ID, type, and 
// length.
int count = 0;
foreach (PropertyItem propItem in propItems)
{
    e.Graphics.DrawString(
    "Property Item " + count.ToString(),
    font,
    blackBrush,
    X, Y);

    Y += font.Height;

    e.Graphics.DrawString(
       "   iD: 0x" + propItem.Id.ToString("x"),
       font,
       blackBrush,
       X, Y);

    Y += font.Height;

    e.Graphics.DrawString(
       "   type: " + propItem.Type.ToString(),
       font,
       blackBrush,
       X, Y);

    Y += font.Height;

    e.Graphics.DrawString(
       "   length: " + propItem.Len.ToString() + " bytes",
       font,
       blackBrush,
       X, Y);

    Y += font.Height;

    count++;
}
// Convert the value of the second property to a string, and display 
// it.
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string manufacturer = encoding.GetString(propItems[1].Value);

e.Graphics.DrawString(
   "The equipment make is " + manufacturer + ".",
   font,
   blackBrush,
   X, Y);

Compilar el código

El ejemplo anterior está diseñado para formularios Windows Forms y requiere PaintEventArgs e, que es un parámetro del controlador de eventos Paint. Reemplace FakePhoto.jpg por un nombre de imagen y una ruta de acceso válidos en el sistema.

Vea también

Otros recursos

Imágenes, mapas de bits y metarchivos

Trabajar con imágenes, mapas de bits, iconos y metarchivos