Introduction
In this post, I will demonstrate how to read image metadata using BitmapMetadata class in C#.
Before staring explanation, we should notice there are two namespaces that can handle image in C#.
- System.Drawing namespace: I tested in this post
- System.Windows.Media.Imaging
Code for Reading Image Metadata
Actually code itself is quite simple :) Please see code below.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Media.Imaging;
using System.Diagnostics;
namespace MetadataExample
{
public static class ReadImageMetadataExample
{
public static void a(string fileName)
{
var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
var img = BitmapFrame.Create(fs);
var metadata = img.Metadata as BitmapMetadata;
Debug.WriteLine("=== metadata ===");
if (metadata == null)
{
Debug.WriteLine("No metadata");
return;
}
Debug.WriteLine("{0}: {1}", new { metadata.ApplicationName }.GetName(), metadata.ApplicationName);
Debug.WriteLine("{0}: {1}", new { metadata.Author }.GetName(), metadata.Author.ToCommaSeparatedString());
Debug.WriteLine("{0}: {1}", new { metadata.CameraManufacturer }.GetName(), metadata.CameraManufacturer);
Debug.WriteLine("{0}: {1}", new { metadata.CameraModel }.GetName(), metadata.CameraModel);
Debug.WriteLine("{0}: {1}", new { metadata.Comment }.GetName(), metadata.Comment);
Debug.WriteLine("{0}: {1}", new { metadata.Copyright }.GetName(), metadata.Copyright);
Debug.WriteLine("{0}: {1}", new { metadata.Keywords }.GetName(), metadata.Keywords.ToCommaSeparatedString());
Debug.WriteLine("{0}: {1}", new { metadata.Location }.GetName(), metadata.Location);
Debug.WriteLine("{0}: {1}", new { metadata.Rating }.GetName(), metadata.Rating);
Debug.WriteLine("{0}: {1}", new { metadata.Subject }.GetName(), metadata.Subject);
Debug.WriteLine("{0}: {1}", new { metadata.Title }.GetName(), metadata.Title);
}
// some trivial helper extension methods to printing out propert info
private static string ToCommaSeparatedString<T>(this ICollection<T> collection)
{
return collection != null ? string.Join(",", collection.ToArray()) : null;
}
private static string GetName<T>(this T item) where T : class
{
return typeof(T).GetProperties()[0].Name;
}
}
}
Example Result
I will show you an execution result of the above C# code.
I passed the image below to the above C# code.
The respective output result of the above image is below.
=== metadata === ApplicationName: Picasa Author: CameraManufacturer: CameraModel: Comment: Test Comments Copyright: Keywords: Location: / Rating: 0 Subject: MetaData Example Title: MetaData Example

コメント