C# 讀取照片的EXIF信息

一、使用 MetadataExtractor 讀取 EXIF 信息

1、NuGet 中安裝

在 NuGet 中搜索並安裝 MetadataExtractor;

2、包信息

我安裝後會有兩個包:MetadataExtractor 2.0.0 和 XmpCore 5.1.3

3、代碼實現

我是創建的 WPF 項目:

private void BTOpen_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\";
    openFileDialog1.Filter = "JPEG|*.jpg;*.jpeg;*.jpe;*.jfif";
    openFileDialog1.FilterIndex = 2;
    openFileDialog1.RestoreDirectory = true;

    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        try
        {
            string filename = openFileDialog1.FileName;
            if (File.Exists(filename))
            {
                TBFile.Text = filename;
                IMImg.Source = new BitmapImage(new Uri(filename, UriKind.Absolute));
                StringBuilder sb = new StringBuilder();
                var directories = ImageMetadataReader.ReadMetadata(filename);
                // print out all metadata
                foreach (var directory in directories)
                    foreach (var tag in directory.Tags)
                        sb.AppendLine($"{directory.Name} - {tag.Name} = {tag.Description}");
                TBInfo.Text = sb.ToString();
            }
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
        }
    }
}
4、效果圖

效果圖

二、簡單的讀取工具類

1、源碼

因爲之前寫過一個照片分類軟件,用過一個簡單的工具類:
在我的 GitHub 中有,地址:C# 工具組 —— EXIF 工具

目錄:Fork/Azylee.Utils/Azylee.Core/IOUtils/ImageUtils/
ExifHelper.cs
ExifTagNames.cs

2、使用代碼:
//一個簡單的Exif信息讀取工具類,根據需要轉換數據類型
ExifHelper exif = new ExifHelper(filename);
foreach (ExifTagNames tag in (ExifTagNames[]) Enum.GetValues(typeof(ExifTagNames)))
{
    double _double = exif.GetPropertyDouble((int)tag);
string _string = exif.GetPropertyString((int)tag);
char _char = '=';// exif.GetPropertyChar((int)tag);
sb.AppendLine($"{tag.ToString()} : {_double} : {_string} : {_char}");
}
sb.AppendLine($"GpsAltitude: {exif.GetPropertyDouble((int)ExifTagNames.GpsAltitude)}"); 
sb.AppendLine($"GpsLatitude: {exif.GetPropertyDouble((int)ExifTagNames.GpsLatitude)}");
sb.AppendLine($"GpsLongitude: {exif.GetPropertyDouble((int)ExifTagNames.GpsLongitude)}");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章