用C#读取(数码相机)图片的EXIF信息 .

对于数码相机所拍摄出的图片,Exif信息非常重要.参考网上的文章,结合我的实际需求,整理了一下,一共三个类文件EXIFextractor .cs,Translation.cs,EXIFMetaData,cs (Translation.cs,EXIFMetaData,cs 参看用C#读取图片的EXIF信息2) 

///EXIFextractor .cs 
using System;
using System.Text;
using System.Collections;
using System.Drawing.Imaging;
using System.Reflection;
using System.IO; 
namespace EXIF
{
/// <summary>
/// EXIFextractor Class
/// </summary>
public class EXIFextractor : IEnumerable
{
/// <summary>
/// Get the individual property value by supplying property name  
/// </summary>
public object this[string index]
{
get
{
return propertiesHash[index];
}
} 
private System.Drawing.Bitmap bmp; 
private string data; //全てのEXIF名と値(項目間に/nで隔てる) 
private Translation myHash; // EXIFタグと名のHashTable  
private Hashtable propertiesHash;// EXIFタグと値のHashTable
internal int Count
{
get
{
return this.propertiesHash.Count;
}
}
//
string separateString;
/// <summary>
/// 
/// </summary>
public void setTag(int id, string data)
{
Encoding ascii = Encoding.ASCII;
this.setTag(id, data.Length, 0x2, ascii.GetBytes(data));
}
/// <summary>
/// setTag
/// </summary>
public void setTag(int id, int len, short type, byte[] data)
{
PropertyItem item = CreatePropertyItem(type, id, len, data);
this.bmp.SetPropertyItem(item);
buildDB(this.bmp.PropertyItems);
}
/// <summary>
/// 
/// </summary>
private static PropertyItem CreatePropertyItem(short type, int tag, int len, byte[] value)
{
PropertyItem item; 

// Loads a PropertyItem from a Jpeg image stored in the assembly as a resource.
Assembly assembly = Assembly.GetExecutingAssembly();
Stream emptyBitmapStream = assembly.GetManifestResourceStream("EXIFextractor.decoy.jpg");
System.Drawing.Image empty = System.Drawing.Image.FromStream(emptyBitmapStream); 

item = empty.PropertyItems[0]; 

// Copies the data to the property item.
item.Type = type;
item.Len = len;
item.Id = tag;
item.Value = new byte[value.Length];
value.CopyTo(item.Value, 0); 

return item;
}
/// <summary>
/// 
/// </summary>
public EXIFextractor(ref System.Drawing.Bitmap bmp, string separate)
{
propertiesHash = new Hashtable();
this.bmp = bmp;
this.separateString = separate; 
myHash = new Translation();
buildDB(this.bmp.PropertyItems);
}
string msp = ""; 

public EXIFextractor(ref System.Drawing.Bitmap bmp, string separate, string msp)
{
propertiesHash = new Hashtable();
this.separateString = separate;
this.msp = msp;
this.bmp = bmp; 
myHash = new Translation();
this.buildDB(bmp.PropertyItems);
}
public static PropertyItem[] GetExifProperties(string fileName)
{
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
System.Drawing.Image image = System.Drawing.Image.FromStream(stream,
/* useEmbeddedColorManagement = */ true,
/* validateImageData = */ false);
return image.PropertyItems;
}
public EXIFextractor(string file, string separate, string msp)
{
propertiesHash = new Hashtable();
this.separateString = separate;
this.msp = msp; 
myHash = new Translation()
this.buildDB(GetExifProperties(file));
} 
/// <summary>
/// データタイプによって、値を取得する。
/// </summary>
private void buildDB(System.Drawing.Imaging.PropertyItem[] parr)
{
propertiesHash.Clear();
//全てのEXIF名と値(項目間に/nで隔てる)
data = ""; 

//ASCII Encoding
Encoding ascii = Encoding.ASCII;
//メタデータプロパティ
foreach (System.Drawing.Imaging.PropertyItem item in parr)
{
string itemValue = "";
string itemName = (string)myHash[item.Id];
// tag not found. skip it
if (itemName == null) continue;
data += itemName + ": ";
//1 = BYTE An 8-bit unsigned integer.,
if (item.Type == 0x1)
{
itemValue = item.Value[0].ToString();
}
//2 = ASCII An 8-bit byte containing one 7-bit ASCII code. The final byte is terminated with NULL.,
else if (item.Type == 0x2)// string  
{ 

itemValue = ascii.GetString(item.Value).Trim('/0');
}
//3 = SHORT A 16-bit (2 -byte) unsigned integer,
else if (item.Type == 0x3)
{ // lookup table  
switch (item.Id)
{
case 0x0112: // Orientation 画像の方向 
{
switch (convertToInt16U(item.Value))
{
case 1: itemValue = "水平(普通)"; break; //1 = Horizontal (normal) 
case 2: itemValue = "水平鏡像"; break; //2 = Mirror horizontal 
case 3: itemValue = "回転180"; break; //3 = Rotate 180 
case 4: itemValue = "垂直鏡像"; break; //4 = Mirror vertical 
case 5: itemValue = "水平鏡像回転270"; break;//5 = Mirror horizontal and rotate 270 CW 
case 6: itemValue = "回転90"; break; //6 = Rotate 90 CW 
case 7: itemValue = "水平鏡像回転90"; break;//7 = Mirror horizontal and rotate 90 CW 
case 8: itemValue = "回転270"; break;//8 = Rotate 270 CW
default: itemValue = "未定義"; break; 
}
}
break; 

case 0x8827: // ISO
itemValue = "ISO-" + convertToInt16U(item.Value).ToString();
break;
case 0xA217: // センサー方式: SensingMethod  
{
switch (convertToInt16U(item.Value))
{
case 1: itemValue = "未定義"; break; //Not defined
case 2: itemValue = "単版カラーセンサー"; break; //One-chip color area sensor
case 3: itemValue = "2板カラーセンサー"; break; //Two-chip color area sensor
case 4: itemValue = "3板カラーセンサー"; break; //Three-chip color area sensor
case 5: itemValue = "色順次カラーセンサー"; break; //Color sequential area sensor
case 7: itemValue = "3線リニアセンサー"; break; //Trilinear sensor
case 8: itemValue = "色順次リニアセンサー"; break; //Color sequential linear sensor
default: itemValue = "保留されます"; break; //reserved
} 
}
break;
case 0xA001://ColorSpace
{
if (convertToInt16U(item.Value) == 1)
{
itemValue = "sRGB";
}
else
{
itemValue = "未調整";//Uncalibrated
}

}
break;
case 0x8822: // 露出プログラム: ExposureProgram  
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "未定義"; break; // Not defined  
case 1: itemValue = "手動"; break; // Manual 
case 2: itemValue = "ノーマルプログラム"; break; // Normal program 
case 3: itemValue = "露出優先"; break;// Aperture priority
case 4: itemValue = "シャッター優先"; break; // Shutter priority
case 5: itemValue = "creativeプログラム(被写界深度方向にバイアス)"; break; // Creative program (biased toward depth of field)
case 6: itemValue = "actionプログラム(シャッタースピード高速側にバイアス)"; break;// Action program (biased toward fast shutter speed)
case 7: itemValue = "ポートレイトモード(クローズアップ撮影、背景はフォーカス外す)"; break; // Portrait mode (for closeup photos with the background out of focus)
case 8: itemValue = "ランドスケープモード(landscape 撮影、背景はフォーカス合う)"; break; // Landscape mode (for landscape photos with the background in focus)
default: itemValue = "保留されます"; break; // reserved
}
break;
case 0x9207: // 測光方式: MeteringMode  
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "不明"; break; // unknown 
case 1: itemValue = "平均"; break; //Average 
case 2: itemValue = "中央重点"; break; // CenterWeightedAverage 
case 3: itemValue = "スポット"; break; // Spot
case 4: itemValue = "マルチスポット"; break; // MultiSpot
case 5: itemValue = "分割測光"; break; // Pattern
case 6: itemValue = "部分測光"; break; // Partial
case 255: itemValue = "その他"; break; // Other
default: itemValue = "保留されます"; break; // reserved
}
break;
case 0x9208: // 光源: LightSource  
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "不明"; break; //unknown
case 1: itemValue = "昼光"; break; //Daylight
case 2: itemValue = "蛍光灯"; break; //Fluorescent
case 3: itemValue = "タングステン"; break; //Tungsten
case 4: itemValue = "フラッシュ*2.2"; break; //flash*2.2
case 9: itemValue = "晴れ*2.2"; break;
case 10: itemValue = "曇り*2.2"; break;
case 11: itemValue = "日陰*2.2"; break;
case 12: itemValue = "Daylight 蛍光灯(D 5700-7100K)*2.2"; break;
case 13: itemValue = "Day white 蛍光灯(N 4600-5400K)*2.2"; break;
case 14: itemValue = "Cool white 蛍光灯(W 3900-4500K)*2.2"; break;
case 15: itemValue = "White 蛍光灯(WW 3200-3700K)*2.2"; break;
case 17: itemValue = "標準光A"; break; //Standard light A
case 18: itemValue = "標準光 B"; break; //Standard light B
case 19: itemValue = "標準光 C"; break; //Standard light C
case 20: itemValue = "D55"; break;
case 21: itemValue = "D65"; break;
case 22: itemValue = "D75"; break;
case 23: itemValue = "D50*2.2"; break;
case 24: itemValue = "ISOスタジオ?タングステン*2.2"; break;
case 255: itemValue = "その他"; break; //other
default: itemValue = "保留されます"; break; //reserved
}
}
break;
case 0x9209://フラッシュ: Flash 
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "フラッシュなし"; break; //No Flash 
case 1: itemValue = "フラッシュ発光"; break; //Flash fired
case 5: itemValue = "発光したが反射光は検出できなかった"; break; //Fired, Return not detected 
case 7: itemValue = "発光したが反射光は検出できなかった"; break; //Fired, Return detected 
case 8: itemValue = "オン、非発光"; break; //On, Did not fire
case 9: itemValue = "オン"; break; // On
case 24: itemValue = "自動、非発光"; break;// Auto, Did not fire 
case 25: itemValue = "自動、発光"; break;// Auto, Fired
case 32: itemValue = "フラッシュ機能なし"; break;// No flash function 
default: itemValue = "未定義"; break; //reserved
}
}
break;
//Exif Version 2.2で新たに規定された項目。
case 0xA401:// スペシャル?エフェクト: CustomRendered  
{
switch (convertToInt16U(item.Value))
{
//スペシャル?エフェクト利用の有無。
case 0: itemValue = "ノーマル処理"; break;
case 1: itemValue = "エフェクトあり"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break;
case 0xA402:// 露光モード: ExposureMode  
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "自動露光"; break;
case 1: itemValue = "手動露光"; break; 
case 2: itemValue = "自動ブラケット"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break;
case 0xA403://ホワイト?バランス: WhiteBalance  
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "自動ホワイト?バランス"; break;
case 1: itemValue = "手動ホワイト?バランス"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break;
case 0xA406://撮影シーン?タイプ: SceneCaptureType  
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "スタンダード"; break;
case 1: itemValue = "ランドスケープ"; break;
case 2: itemValue = "ポートレイト"; break;
case 3: itemValue = "夜景"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break; 
case 0xA408://コントラスト: Contrast  
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "ノーマル"; break;
case 1: itemValue = "ソフト"; break;
case 2: itemValue = "ハード"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break;
case 0xA409://飽和状態: Saturation  
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "ノーマル"; break;
case 1: itemValue = "低飽和"; break;
case 2: itemValue = "高飽和"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break;
case 0xA40A://シャープネス: Sharpness  
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "ノーマル"; break;
case 1: itemValue = "ソフト"; break;
case 2: itemValue = "ハード"; break;
case 3: itemValue = "夜景"; break;
case 4: itemValue = "夜景"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break;
case 0xA40C://被写体撮影モード: SubjectDistanceRange  
{
switch (convertToInt16U(item.Value))
{
case 0: itemValue = "不明"; break;
case 1: itemValue = "マクロ"; break;
case 2: itemValue = "近景"; break;
case 3: itemValue = "遠景"; break;
case 4: itemValue = "夜景"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break;
default:
itemValue = convertToInt16U(item.Value).ToString();
break;
}
}
//4 = LONG A 32-bit (4 -byte) unsigned integer,
else if (item.Type == 0x4)
{ 
itemValue = convertToInt32U(item.Value).ToString();
}
//5 = RATIONAL Two LONGs. The first LONG is the numerator and the second LONG expresses the//denominator.,
else if (item.Type == 0x5)
{
// rational
byte[] n = new byte[item.Len / 2];
byte[] d = new byte[item.Len / 2];
Array.Copy(item.Value, 0, n, 0, item.Len / 2);
Array.Copy(item.Value, item.Len / 2, d, 0, item.Len / 2);
uint a = convertToInt32U(n);
uint b = convertToInt32U(d);
Rational r = new Rational(a, b); 
//convert here  
switch (item.Id)
{
case 0x9202: // 絞り(APEX) aperture
itemValue = "F" + Math.Round(Math.Pow(Math.Sqrt(2), r.ToDouble()), 2).ToString();
break;
case 0x920A://レンズ焦点距離: FocalLength  
itemValue = r.ToDouble().ToString()+" mm";
break;
case 0x829A://露出時間: ExposureTime  
itemValue = r.ToString("/") + "";
break;
case 0x829D: // F-number
itemValue = "F/" + r.ToDouble().ToString();
break;
//Exif Version 2.2で新たに規定された項目。
case 0xA407://ゲイン?コントロール: GainControl  
{
switch ((int)r.ToDouble())
{
case 0: itemValue = "コントロールなし"; break;
case 1: itemValue = "低ゲイン?アップ"; break;
case 2: itemValue = "高ゲイン?アップ"; break;
case 3: itemValue = "低ゲイン?ダウン"; break;
case 4: itemValue = "高ゲイン?ダウン"; break;
default: itemValue = "未定義"; break; //reserved
}
}
break;
default:
itemValue = r.ToString("/");
break;
} 

}
//7 = UNDEFINED An 8-bit byte that can take any value depending on the field definition,
else if (item.Type == 0x7)
{
switch (item.Id)
{
case 0xA300://ファイルソース: FileSource  
{
if (item.Value[0] == 3)
{
itemValue = "デジタルカメラ";
}
else
{
itemValue = "保留されます";
}
break;
}
case 0xA301://シーンタイプ: SceneType  
if (item.Value[0] == 1)
// a directly photographed image
itemValue = "直接撮影された画像";
else
//Not a directly photographed image
itemValue = "直接撮影された画像ではない";
break;
case 0x9101://各コンポーネントの意味: ComponentsConfiguration  
// 0x04050600 : RGB / 0x01020300 : YCbCr 
string temp = BitConverter.ToString(item.Value).Substring(0,11);
switch (temp)
{
case "01-02-03-00":
itemValue = "RGB";
break;
case "04-05-06-00":
itemValue = "YCbCr";
break;
default:
itemValue = "未定義";
break;
}
break;
case 0x9286://ユーザーコメント 
// ただし始めの8バイトは文字コードを示す。
string usercomment= BitConverter.ToString(item.Value).Substring(0,23);
switch (usercomment)
{
case "41-53-43-49-49-00-00-00":
itemValue = "ASCII";
break;
case "4A-49-53-00-00-00-00-00":
itemValue = "JIS";
break;
case "55-4E-49-43-4F-44-45-00":
itemValue = "Unicode";
break;
default:
itemValue = "未定義";
break;
}
break;
default:
itemValue = "-";
break;
}
} 
//9 = SLONG A 32-bit (4 -byte) signed integer (2's complement notation),
else if (item.Type == 0x9)
{
itemValue = convertToInt32(item.Value).ToString();
}
//10 = SRATIONAL Two SLONGs. The first SLONG is the numerator and the second SLONG is the
//denominator.
else if (item.Type == 0xA)
{
// unsigned rational
byte[] n = new byte[item.Len / 2];
byte[] d = new byte[item.Len / 2];
Array.Copy(item.Value, 0, n, 0, item.Len / 2);
Array.Copy(item.Value, item.Len / 2, d, 0, item.Len / 2);
int a = convertToInt32(n);
int b = convertToInt32(d);
Rational r = new Rational(a, b); 

// convert here
switch (item.Id)
{
case 0x9201: // シャッタースピード: ShutterSpeedValue 
itemValue = "1/" + Math.Round(Math.Pow(2, r.ToDouble()), 2).ToString()+"sec";
break;
case 0x9203://輝度値: BrightnessValue  
itemValue = Math.Round(r.ToDouble(), 4).ToString();
break;
default:
itemValue = r.ToString("/");
break;
}
}
// リストに追加する。
if (propertiesHash[itemName] == null)
propertiesHash.Add(itemName, itemValue);
// cat it too
data += itemValue;
data += this.separateString;
}
}
/// <summary>
/// 全ての項目と項目の値(項目間に/nで隔てる)を取得する。
/// </summary>
/// <returns></returns>
public override string ToString()
{
return data;
} 
/// <summary>
/// 16-bit (2 -byte) signed short
/// </summary>
int convertToInt16(byte[] arr)
{
if (arr.Length != 2)
return 0;
else
return arr[1] << 8 | arr[0];
}
/// <summary>
/// SHORT:16-bit (2 -byte) unsigned integer
/// </summary>
uint convertToInt16U(byte[] arr)
{
if (arr.Length != 2)
return 0;
else
return Convert.ToUInt16(arr[1] << 8 | arr[0]);
} 

/// <summary>
/// SLONG: 32-bit (4 -byte) signed integer (2's complement notation)
/// </summary>
int convertToInt32(byte[] arr)
{
if (arr.Length != 4)
return 0;
else
return arr[3] << 24 | arr[2] << 16 | arr[1] << 8 | arr[0];
}
/// <summary>
/// LONG: 32-bit (4 -byte) unsigned integer
/// </summary>
uint convertToInt32U(byte[] arr)
{
if (arr.Length != 4)
return 0;
else
return Convert.ToUInt32(arr[3] << 24 | arr[2] << 16 | arr[1] << 8 | arr[0]);
} 
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
// TODO: Add EXIFextractor.GetEnumerator implementation
return (new EXIFextractorEnumerator(this.propertiesHash));
}
#endregion
} 

#region EXIFextractorEnumerator class
/// <summary>
///dont touch this class. its for IEnumerator
/// </summary>
class EXIFextractorEnumerator : IEnumerator
{
Hashtable exifTable;
IDictionaryEnumerator index; 

internal EXIFextractorEnumerator(Hashtable exif)
{
this.exifTable = exif;
this.Reset();
index = exif.GetEnumerator();
} 

#region IEnumerator Members
public void Reset()
{
this.index = null;
} 
public object Current
{
get
{
return (new Pair(this.index.Key, this.index.Value));
}
} 

public bool MoveNext()
{
if (index != null && index.MoveNext())
return true;
else
return false;
} 
#endregion
}
#endregion 

#region Pair class
public class Pair
{
public string First;
public string Second;
public Pair(object key, object value)
{
this.First = key.ToString();
this.Second = value.ToString();
}
}
#endregion
}

 

http://artemismingr.spaces.live.com/?_c11_BlogPart_pagedir=Next&_c11_BlogPart_handle=cns!69B8ABCD57092B10!1810&_c11_BlogPart_BlogPart=blogview&_c=BlogPart 

 

 

用C#读取图片的EXIF信息2 
///translation.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace EXIF
{
    /// <summary>
    /// Summary description for translation.
    /// </summary>
    public class Translation : Hashtable
    {
        /// <summary>
        /// 
        /// </summary>
        public Translation()
        {
            //IFD0 (main image) で使われているTag
            this.Add(0x010e, "ImageDescription");// 画像タイトル 
            this.Add(0x010f, "Make");//  メーカ 
            this.Add(0x0110, "Model");//  モデル           
            this.Add(0x011a, "XResolution");// 画像の幅方向の解像度(ピクセル) 
            this.Add(0x011b, "YResolution");// 画像の高さ方向の解像度(ピクセル)
            this.Add(0x0128, "ResolutionUnit");// 解像度の単位 
            this.Add(0x0131, "Software");//  使用したソフトウェア 
            this.Add(0x0132, "ExifDateTime");//  ファイル変更日時
            this.Add(0x013f, "PrimaryChromaticities");//  原色の色座標値           
            this.Add(0x8298, "Copyright");//  著作権表示 
            this.Add(0x8769, "ExifIFDPointer");// Exif IFD へのポインタ 
            //Exif SubIFD で使われているTag
            this.Add(0x829a, "ExposureTime");// 露出時間(秒) 
            this.Add(0x829d, "FNumber");// F値 
            this.Add(0x8822, "ExposureProgram");// 露出プログラム 
            this.Add(0x8824, "SpectralSensitivity");// スペクトル感度
            this.Add(0x8827, "ISOSpeedRatings");// ISOスピードレート 
            this.Add(0x9000, "ExifVersion");// Exifバージョン 
            this.Add(0x9003, "DateTimeOriginal");// オリジナル画像の生成日時 
            this.Add(0x9004, "DateTimeDigitized");// ディジタルデータの生成日時 
            this.Add(0x9101, "ComponentsConfiguration");// コンポーネントの意味 
            this.Add(0x9102, "CompressedBitsPerPixel");// 画像圧縮モード(ビット/ピクセル)
            this.Add(0x9201, "ShutterSpeedValue");// シャッタースピード(APEX) 
            this.Add(0x9202, "ApertureValue");// 絞り(APEX) 
            this.Add(0x9203, "BrightnessValue");//輝度(APEX) 
            this.Add(0x9204, "ExposureBiasValue");// 露出補正(APEX) 
            this.Add(0x9205, "MaxApertureValue");// レンズの最小F値(APEX) 
            this.Add(0x9206, "SubjectDistance");// 被写体距離(m) 
            this.Add(0x9207, "MeteringMode");//測光方式 
            this.Add(0x9208, "LightSource");// 光源 
            this.Add(0x9209, "Flash");// フラッシュ 
            this.Add(0x920a, "FocalLength");// レンズの焦点距離(mm) 
            this.Add(0x927c, "MakerNote"); //メーカ固有情報 
            this.Add(0x9286, "UserComment");// ユーザコメント 
            this.Add(0x9290, "SubSecTime");//ファイル変更日時の秒以下の値 
            this.Add(0x9291, "SubSecTimeOriginal");// 画像生成日時の秒以下の値 
            this.Add(0x9292, "SubSecTimeDigitized");// ディジタルデータ生成日時の秒以下の値 
            this.Add(0xa000, "FlashPixVersion");// 対応FlashPixのバージョン 
            this.Add(0xa001, "ColorSpace");// 色空間情報 
            this.Add(0xa002, "ExifImageWidth ");// メイン画像の幅 
            this.Add(0xa003, "ExifImageHeight ");//  メイン画像の高さ
            this.Add(0xa004, "RelatedSoundFile");// 関連音声ファイル名 
            this.Add(0xa005, "InteroperabilityIFDPointer");// 互換性IFDへのポインタ 
            this.Add(0xa20e, "FocalPlaneXResolution");// 焦点面の幅方向の解像度(ピクセル) 
            this.Add(0xa20f, "FocalPlaneYResolution");// 焦点面の高さ方向の解像度(ピクセル) 
            this.Add(0xa210, "FocalPlaneResolutionUnit");// 焦点面の解像度の単位  
            this.Add(0xa215, "ExposureIndex");// 露出インデックス 
            this.Add(0xa217, "SensingMethod");// 画像センサの方式 
            this.Add(0xa300, "FileSource");// 画像入力機器の種類 
            this.Add(0xa301, "SceneType");//シーンタイプ 
            this.Add(0xa302, "CFAPattern");//CFAパターン 
            //IFD1 (thumbnail image) で使われているTag
            this.Add(0x0100, "ImageWidth ");// 画像の幅(ピクセル) 
            this.Add(0x0101, "ImageHeight ");//  画像の高さ(ピクセル)
            this.Add(0x0102, "BitsPerSample");//  画素のビットの深さ(ビット) 
            this.Add(0x0103, "Compression");// 圧縮の種類 
            this.Add(0x0106, "PhotometricInterpretation");//  画素構成の種類   
            this.Add(0x0111, "StripOffsets");// イメージデータへのオフセット 
            this.Add(0x0112, "Orientation");// 画素の並び 
            this.Add(0x0115, "SamplesPerPixel");//  ピクセル毎のコンポーネント数 
            this.Add(0x0116, "RowsPerStrip");//  1ストリップあたりの行数 
            this.Add(0x0117, "StripByteCounts");// 各ストリップのサイズ(バイト)
            this.Add(0x011c, "PlanarConfiguration");//  画素データの並び
            this.Add(0x0201, "JPEGInterchangeFormat");//  JPEGサムネイルのSOIへのオフセット 
            this.Add(0x0202, "JPEGInterchangeFormatLength");//  JPEGサムネイルデータのサイズ(バイト
            this.Add(0x0211, "YCbCrCoefficients");//  色変換マトリックス係数 
            this.Add(0x0212, "YCbCrSubSampling");// 画素の比率構成  
            this.Add(0x0213, "YCbCrPositioning ");//  色情報のサンプリング
            this.Add(0x0214, "ReferenceBlackWhite");//  黒色と白色の値 
            //その他のTag
            this.Add(0x00fe, "NewSubfileType");
            this.Add(0x00ff, "SubfileType");
            this.Add(0x012d, "TransferFunction");//  諧調カーブ特性 
            this.Add(0x013b, "Artist");//  撮影者名
            this.Add(0x013d, "Predictor");
            this.Add(0x013e, "WhitePoint");//  ホワイトポイントの色座標値 
            this.Add(0x0142, "TileWidth");
            this.Add(0x0143, "TileLength");
            this.Add(0x0144, "TileOffsets");
            this.Add(0x0145, "TileByteCounts");
            this.Add(0x014a, "SubIFDs");
            this.Add(0x015b, "JPEGTables");
            this.Add(0x828d, "CFARepeatPatternDim");
            this.Add(0x828f, "BatteryLevel ");
            this.Add(0x83bb, "IPTC/NAA");
            this.Add(0x8773, "InterColorProfile");
            this.Add(0x8825, "GPSInfo");// GPS情報IFDへのポインタ
            this.Add(0x8828, "OECF");// 光電変換関数 
            this.Add(0x8829, "Interlace");
            this.Add(0x882a, "TimeZoneOffset");
            this.Add(0x882b, "SelfTimerMode");
            this.Add(0x920b, "FlashEnergy ");// フラッシュのエネルギー(BCPS)
            this.Add(0x920c, "SpatialFrequencyResponse");//空間周波数応答 
            this.Add(0x920d, "Noise");
            this.Add(0x9211, "ImageNumber");
            this.Add(0x9212, "SecurityClassification");
            this.Add(0x9213, "ImageHistory");
            this.Add(0x9214, "SubjectLocation");//被写体位置
            this.Add(0x9216, "TIFFEPStandardID");
            //Interoperability IFD で使われているTag
            this.Add(0x0001, "InteroperabilityIndex");
            this.Add(0x0002, "InteroperabilityVersion");
            this.Add(0x1000, "RelatedImageFileFormat");
        }
    }
    /// <summary>
    /// private class
    /// RATIONAL Two LONGs. The first LONG is the numerator and the second LONG expresses the denominator.
    /// </summary>
    internal class Rational
    {
        private int n;
        private int d;
        public Rational(int n, int d)
        {
            this.n = n;
            this.d = d;
            simplify(ref this.n, ref this.d);
        }
        public Rational(uint n, uint d)
        {
            this.n = Convert.ToInt32(n);
            this.d = Convert.ToInt32(d);
            simplify(ref this.n, ref this.d);
        }
        public Rational()
        {
            this.n = this.d = 0;
        }
        public string ToString(string sp)
        {
            if (sp == null) sp = "/";
            return n.ToString() + sp + d.ToString();
        }
        public double ToDouble()
        {
            if (d == 0)
                return 0.0;
            return Math.Round(Convert.ToDouble(n) / Convert.ToDouble(d), 2);
        }
        private void simplify(ref int a, ref int b)
        {
            if (a == 0 || b == 0)
                return;
            int gcd = euclid(a, b);
            a /= gcd;
            b /= gcd;
        }
        private int euclid(int a, int b)
        {
            if (b == 0)
                return a;
            else
                return euclid(b, a % b);
        }
    }
}

 
// 
 EXIFMetaData.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.IO;
using EXIF;
using System.Collections.Specialized;
namespace PictureView
{
    class EXIFMetaData
    {
        public EXIFMetaData()
        {
        }
        #region struct MetadataDetail
        /// <summary>
        /// 構造体
        /// </summary>
        public struct MetadataDetail
        {
            //public string RawValueAsString;//原文字列
            public string DisplayValue;//
        }
        #endregion
        #region EXIF Element
        /// <summary>
        ///  EXIF Elementを保存した
        /// </summary>
        public struct Metadata
        {
            //IFD0 (main image) で使われているTag
            public MetadataDetail ImageDescription;// 画像タイトル 
            public MetadataDetail Make;//  メーカ 
            public MetadataDetail Model;//  モデル   
            public MetadataDetail XResolution;// 画像の幅方向の解像度(ピクセル) 
            public MetadataDetail YResolution;// 画像の高さ方向の解像度(ピクセル)
            public MetadataDetail ResolutionUnit;// 解像度の単位 
            public MetadataDetail Software;//  使用したソフトウェア 
            public MetadataDetail ExifDateTime;//  ファイル変更日時
            public MetadataDetail PrimaryChromaticities;//  原色の色座標値   
            public MetadataDetail Copyright;//  著作権表示 
            public MetadataDetail ExifIFDPointer;// Exif IFD へのポインタ 
            //Exif SubIFD で使われているTag
            public MetadataDetail ExposureTime;// 露出時間(秒) 
            public MetadataDetail FNumber;// F値 
            public MetadataDetail ExposureProgram;// 露出プログラム 
            public MetadataDetail SpectralSensitivity;// スペクトル感度
            public MetadataDetail ISOSpeedRatings;// ISOスピードレート 
            public MetadataDetail ExifVersion;// Exifバージョン 
            public MetadataDetail DateTimeOriginal;// オリジナル画像の生成日時 
            public MetadataDetail DateTimeDigitized;// ディジタルデータの生成日時 
            public MetadataDetail ComponentsConfiguration;// コンポーネントの意味 
            public MetadataDetail CompressedBitsPerPixel;// 画像圧縮モード(ビット/ピクセル)
            public MetadataDetail ShutterSpeedValue;// シャッタースピード(APEX) 
            public MetadataDetail ApertureValue;// 絞り(APEX) 
            public MetadataDetail BrightnessValue;//輝度(APEX) 
            public MetadataDetail ExposureBiasValue;// 露出補正(APEX) 
            public MetadataDetail MaxApertureValue;// レンズの最小F値(APEX) 
            public MetadataDetail SubjectDistance;// 被写体距離(m) 
            public MetadataDetail MeteringMode;//測光方式 
            public MetadataDetail LightSource;// 光源 
            public MetadataDetail Flash;// フラッシュ 
            public MetadataDetail FocalLength;// レンズの焦点距離(mm) 
            public MetadataDetail MakerNote; //メーカ固有情報 
            public MetadataDetail UserComment;// ユーザコメント 
            public MetadataDetail SubSecTime;//ファイル変更日時の秒以下の値 
            public MetadataDetail SubSecTimeOriginal;// 画像生成日時の秒以下の値 
            public MetadataDetail SubSecTimeDigitized;// ディジタルデータ生成日時の秒以下の値 
            public MetadataDetail FlashPixVersion;// 対応FlashPixのバージョン 
            public MetadataDetail ColorSpace;// 色空間情報 
            public MetadataDetail ExifImageWidth;// メイン画像の幅 
            public MetadataDetail ExifImageHeight;//  メイン画像の高さ
            public MetadataDetail RelatedSoundFile;// 関連音声ファイル名 
            public MetadataDetail InteroperabilityIFDPointer;// 互換性IFDへのポインタ 
            public MetadataDetail FocalPlaneXResolution;// 焦点面の幅方向の解像度(ピクセル) 
            public MetadataDetail FocalPlaneYResolution;// 焦点面の高さ方向の解像度(ピクセル) 
            public MetadataDetail FocalPlaneResolutionUnit;// 焦点面の解像度の単位  
            public MetadataDetail ExposureIndex;// 露出インデックス 
            public MetadataDetail SensingMethod;// 画像センサの方式 
            public MetadataDetail FileSource;// 画像入力機器の種類 
            public MetadataDetail SceneType;//シーンタイプ 
            public MetadataDetail CFAPattern;//CFAパターン 
            //IFD1 (thumbnail image) で使われているTag
            public MetadataDetail ImageWidth;// 画像の幅(ピクセル) 
            public MetadataDetail ImageHeight;//  画像の高さ(ピクセル)
            public MetadataDetail BitsPerSample;//  画素のビットの深さ(ビット) 
            public MetadataDetail Compression;// 圧縮の種類 
            public MetadataDetail PhotometricInterpretation;//  画素構成の種類   
            public MetadataDetail StripOffsets;// イメージデータへのオフセット 
            public MetadataDetail Orientation;// 画素の並び 
            public MetadataDetail SamplesPerPixel;//  ピクセル毎のコンポーネント数 
            public MetadataDetail RowsPerStrip;//  1ストリップあたりの行数 
            public MetadataDetail StripByteCounts;// 各ストリップのサイズ(バイト)
            public MetadataDetail PlanarConfiguration;//  画素データの並び
            public MetadataDetail JPEGInterchangeFormat;//  JPEGサムネイルのSOIへのオフセット 
            public MetadataDetail JPEGInterchangeFormatLength;//  JPEGサムネイルデータのサイズ(バイト
            public MetadataDetail YCbCrCoefficients;//  色変換マトリックス係数 
            public MetadataDetail YCbCrSubSampling;// 画素の比率構成  
            public MetadataDetail YCbCrPositioning;//  色情報のサンプリング
            public MetadataDetail ReferenceBlackWhite;//  黒色と白色の値 
            //その他
            public MetadataDetail NewSubfileType;
            public MetadataDetail SubfileType;
            public MetadataDetail TransferFunction;//  諧調カーブ特性 
            public MetadataDetail Artist;//  撮影者名
            public MetadataDetail Predictor;
            public MetadataDetail WhitePoint;//  ホワイトポイントの色座標値 ;
            public MetadataDetail TileWidth;
            public MetadataDetail TileLength;
            public MetadataDetail TileOffsets;
            public MetadataDetail TileByteCounts;
            public MetadataDetail SubIFDs;
            public MetadataDetail JPEGTables;
            public MetadataDetail CFARepeatPatternDim;
            public MetadataDetail BatteryLevel;
            public MetadataDetail IPTCNAA;
            public MetadataDetail InterColorProfile;
            public MetadataDetail GPSInfo;// GPS情報IFDへのポインタ
            public MetadataDetail OECF;// 光電変換関数 
            public MetadataDetail Interlace;
            public MetadataDetail TimeZoneOffset;
            public MetadataDetail SelfTimerMode;
            public MetadataDetail FlashEnergy;// フラッシュのエネルギー(BCPS)
            public MetadataDetail SpatialFrequencyResponse;//空間周波数応答 
            public MetadataDetail Noise;
            public MetadataDetail ImageNumber;
            public MetadataDetail SecurityClassification;
            public MetadataDetail ImageHistory;
            public MetadataDetail SubjectLocation;//被写体位置
            public MetadataDetail TIFFEPStandardID;
            //Interoperability IFD で使われているTag
            public MetadataDetail InteroperabilityIndex;
            public MetadataDetail InteroperabilityVersion;
            public MetadataDetail RelatedImageFileFormat;
        }
        #endregion
        #region EXIF情報を取得
        public Metadata GetEXIFMetaData(string PhotoName)
        {
            // 
            Bitmap MyImage = (Bitmap)Bitmap.FromFile(PhotoName);
            EXIFextractor exifExtractor = new EXIFextractor(ref MyImage, "/n");
            NameValueCollection items = new NameValueCollection();
            foreach (Pair pair in exifExtractor)
            {
                items.Add(pair.First, pair.Second);
            }
            Metadata MyMetadata = new Metadata();
            try
            {
                MyMetadata.ImageDescription.DisplayValue = items.Get("ImageDescription");// 画像タイトル 
                MyMetadata.Make.DisplayValue = items.Get("Make");//  メーカ 
                MyMetadata.Model.DisplayValue = items.Get("Model");//  モデル   
                //MyMetadata.XResolution.DisplayValue = items.Get("XResolution");// 画像の幅方向の解像度(ピクセル) 
                //MyMetadata.YResolution.DisplayValue = items.Get("YResolution");// 画像の高さ方向の解像度(ピクセル)
                MyMetadata.XResolution.DisplayValue = MyImage.HorizontalResolution.ToString();
                MyMetadata.YResolution.DisplayValue = MyImage.VerticalResolution.ToString();
                MyMetadata.ResolutionUnit.DisplayValue = items.Get("ResolutionUnit");// 解像度の単位 
                MyMetadata.Software.DisplayValue = items.Get("Software");//  使用したソフトウェア 
                MyMetadata.ExifDateTime.DisplayValue = items.Get("ExifDateTime");//  ファイル変更日時
                MyMetadata.PrimaryChromaticities.DisplayValue = items.Get("PrimaryChromaticities");//  原色の色座標値   
                MyMetadata.Copyright.DisplayValue = items.Get("Copyright");//  著作権表示 
                MyMetadata.ExifIFDPointer.DisplayValue = items.Get("ExifIFDPointer");// Exif IFD へのポインタ 
                MyMetadata.ExposureTime.DisplayValue = items.Get("ExposureTime");// 露出時間(秒) 
                MyMetadata.FNumber.DisplayValue = items.Get("FNumber");// F値 
                MyMetadata.ExposureProgram.DisplayValue = items.Get("ExposureProgram");// 露出プログラム 
                MyMetadata.SpectralSensitivity.DisplayValue = items.Get("SpectralSensitivity");// スペクトル感度
                MyMetadata.ISOSpeedRatings.DisplayValue = items.Get("ISOSpeedRatings");// ISOスピードレート 
                MyMetadata.ExifVersion.DisplayValue = items.Get("ExifVersion");// Exifバージョン 
                MyMetadata.DateTimeOriginal.DisplayValue = items.Get("DateTimeOriginal");// オリジナル画像の生成日時 
                MyMetadata.DateTimeDigitized.DisplayValue = items.Get("DateTimeDigitized");// ディジタルデータの生成日時 
                MyMetadata.ComponentsConfiguration.DisplayValue = items.Get("ComponentsConfiguration");// コンポーネントの意味 
                MyMetadata.CompressedBitsPerPixel.DisplayValue = items.Get("CompressedBitsPerPixel");// 画像圧縮モード(ビット/ピクセル)
                MyMetadata.ShutterSpeedValue.DisplayValue = items.Get("ShutterSpeedValue");// シャッタースピード(APEX) 
                MyMetadata.ApertureValue.DisplayValue = items.Get("ApertureValue");// 絞り(APEX) 
                MyMetadata.BrightnessValue.DisplayValue = items.Get("BrightnessValue");//輝度(APEX) 
                MyMetadata.ExposureBiasValue.DisplayValue = items.Get("ExposureBiasValue");// 露出補正(APEX) 
                MyMetadata.MaxApertureValue.DisplayValue = items.Get("MaxApertureValue");// レンズの最小F値(APEX) 
                MyMetadata.SubjectDistance.DisplayValue = items.Get("SubjectDistance");// 被写体距離(m) 
                MyMetadata.MeteringMode.DisplayValue = items.Get("MeteringMode");//測光方式 
                MyMetadata.LightSource.DisplayValue = items.Get("LightSource");// 光源 
                MyMetadata.Flash.DisplayValue = items.Get("Flash");// フラッシュ 
                MyMetadata.FocalLength.DisplayValue = items.Get("FocalLength");// レンズの焦点距離(mm) 
                MyMetadata.MakerNote.DisplayValue = items.Get("MakerNote"); //メーカ固有情報 
                MyMetadata.UserComment.DisplayValue = items.Get("UserComment");// ユーザコメント 
                MyMetadata.SubSecTime.DisplayValue = items.Get("SubSecTime");//ファイル変更日時の秒以下の値 
                MyMetadata.SubSecTimeOriginal.DisplayValue = items.Get("SubSecTimeOriginal");// 画像生成日時の秒以下の値 
                MyMetadata.SubSecTimeDigitized.DisplayValue = items.Get("SubSecTimeDigitized");// ディジタルデータ生成日時の秒以下の値 
                MyMetadata.FlashPixVersion.DisplayValue = items.Get("FlashPixVersion");// 対応FlashPixのバージョン 
                MyMetadata.ColorSpace.DisplayValue = items.Get("ColorSpace");// 色空間情報 
                MyMetadata.ExifImageWidth.DisplayValue = items.Get("ExifImageWidth ");// メイン画像の幅 
                MyMetadata.ExifImageHeight.DisplayValue = items.Get("ExifImageHeight ");//  メイン画像の高さ
                MyMetadata.RelatedSoundFile.DisplayValue = items.Get("RelatedSoundFile");// 関連音声ファイル名 
                MyMetadata.InteroperabilityIFDPointer.DisplayValue = items.Get("InteroperabilityIFDPointer");// 互換性IFDへのポインタ 
                MyMetadata.FocalPlaneXResolution.DisplayValue = items.Get("FocalPlaneXResolution");// 焦点面の幅方向の解像度(ピクセル) 
                MyMetadata.FocalPlaneYResolution.DisplayValue = items.Get("FocalPlaneYResolution");// 焦点面の高さ方向の解像度(ピクセル) 
                MyMetadata.FocalPlaneResolutionUnit.DisplayValue = items.Get("FocalPlaneResolutionUnit");// 焦点面の解像度の単位  
                MyMetadata.ExposureIndex.DisplayValue = items.Get("ExposureIndex");// 露出インデックス 
                MyMetadata.SensingMethod.DisplayValue = items.Get("SensingMethod");// 画像センサの方式 
                MyMetadata.FileSource.DisplayValue = items.Get("FileSource");// 画像入力機器の種類 
                MyMetadata.SceneType.DisplayValue = items.Get("シーSceneType");//シーンタイプ 
                MyMetadata.CFAPattern.DisplayValue = items.Get("CFACFAPattern");//CFAパターン 
                MyMetadata.ImageWidth.DisplayValue = items.Get("ImageWidth");// 画像の幅(ピクセル) 
                MyMetadata.ImageHeight.DisplayValue = items.Get("ImageHeight");//  画像の高さ(ピクセル)
                MyMetadata.BitsPerSample.DisplayValue = items.Get("BitsPerSample");//  画素のビットの深さ(ビット) 
                MyMetadata.Compression.DisplayValue = items.Get("Compression");// 圧縮の種類 
                MyMetadata.PhotometricInterpretation.DisplayValue = items.Get("PhotometricInterpretation");//  画素構成の種類   
                MyMetadata.StripOffsets.DisplayValue = items.Get("StripOffsets");// イメージデータへのオフセット 
                MyMetadata.Orientation.DisplayValue = items.Get("Orientation");// 画素の並び 
                MyMetadata.SamplesPerPixel.DisplayValue = items.Get("SamplesPerPixel");//  ピクセル毎のコンポーネント数 
                MyMetadata.RowsPerStrip.DisplayValue = items.Get("RowsPerStrip");//  1ストリップあたりの行数 
                MyMetadata.StripByteCounts.DisplayValue = items.Get("StripByteCounts");// 各ストリップのサイズ(バイト)
                MyMetadata.PlanarConfiguration.DisplayValue = items.Get("PlanarConfiguration");//  画素データの並び
                MyMetadata.JPEGInterchangeFormat.DisplayValue = items.Get("JPEGInterchangeFormat");//  JPEGサムネイルのSOIへのオフセット 
                MyMetadata.JPEGInterchangeFormatLength.DisplayValue = items.Get("JPEGInterchangeFormatLength");//  JPEGサムネイルデータのサイズ(バイト
                MyMetadata.YCbCrCoefficients.DisplayValue = items.Get("YCbCrCoefficients");//  色変換マトリックス係数 
                MyMetadata.YCbCrSubSampling.DisplayValue = items.Get("YCbCrSubSampling");// 画素の比率構成  
                MyMetadata.YCbCrPositioning.DisplayValue = items.Get("YCbCrPositioning ");//  色情報のサンプリング
                MyMetadata.ReferenceBlackWhite.DisplayValue = items.Get("ReferenceBlackWhite");//  黒色と白色の値 
                MyMetadata.NewSubfileType.DisplayValue = items.Get("NewSubfileType");
                MyMetadata.SubfileType.DisplayValue = items.Get("SubfileType");
                MyMetadata.TransferFunction.DisplayValue = items.Get("TransferFunction");//  諧調カーブ特性 
                MyMetadata.Artist.DisplayValue = items.Get("Artist");//  撮影者名
                MyMetadata.Predictor.DisplayValue = items.Get("Predictor");
                MyMetadata.WhitePoint.DisplayValue = items.Get("WhitePoint");//  ホワイトポイントの色座標値 
                MyMetadata.TileWidth.DisplayValue = items.Get("TileWidth");
                MyMetadata.TileLength.DisplayValue = items.Get("TileLength");
                MyMetadata.TileOffsets.DisplayValue = items.Get("TileOffsets");
                MyMetadata.TileByteCounts.DisplayValue = items.Get("TileByteCounts");
                MyMetadata.SubIFDs.DisplayValue = items.Get("SubIFDs");
                MyMetadata.JPEGTables.DisplayValue = items.Get("JPEGTables");
                MyMetadata.CFARepeatPatternDim.DisplayValue = items.Get("CFARepeatPatternDim");
                MyMetadata.BatteryLevel.DisplayValue = items.Get("BatteryLevel ");
                MyMetadata.IPTCNAA.DisplayValue = items.Get("IPTCNAA");
                MyMetadata.InterColorProfile.DisplayValue = items.Get("InterColorProfile");
                MyMetadata.GPSInfo.DisplayValue = items.Get("GPSInfo");// GPS情報IFDへのポインタ
                MyMetadata.OECF.DisplayValue = items.Get("OECF");// 光電変換関数 
                MyMetadata.Interlace.DisplayValue = items.Get("Interlace");
                MyMetadata.TimeZoneOffset.DisplayValue = items.Get("TimeZoneOffset");
                MyMetadata.SelfTimerMode.DisplayValue = items.Get("SelfTimerMode");
                MyMetadata.FlashEnergy.DisplayValue = items.Get("FlashEnergy ");// フラッシュのエネルギー(BCPS)
                MyMetadata.SpatialFrequencyResponse.DisplayValue = items.Get("SpatialFrequencyResponse");//空間周波数応答 
                MyMetadata.Noise.DisplayValue = items.Get("Noise ");
                MyMetadata.ImageNumber.DisplayValue = items.Get("ImageNumber");
                MyMetadata.SecurityClassification.DisplayValue = items.Get("SecurityClassification");
                MyMetadata.ImageHistory.DisplayValue = items.Get("ImageHistory");
                MyMetadata.SubjectLocation.DisplayValue = items.Get("SubjectLocation");//被写体位置
                MyMetadata.TIFFEPStandardID.DisplayValue = items.Get("TIFFEPStandardID");
                MyMetadata.InteroperabilityIndex.DisplayValue = items.Get("InteroperabilityIndex");
                MyMetadata.InteroperabilityVersion.DisplayValue = items.Get("InteroperabilityVersion");
                MyMetadata.RelatedImageFileFormat.DisplayValue = items.Get("RelatedImageFileFormat");
            }
            catch
            { 
            }
            items.Clear();
            return MyMetadata;
        }
        #endregion
    }
}

 

posted @ 2012-08-30 11:07  许明吉博客  阅读(3347)  评论(1编辑  收藏  举报