2017-07-18 106 views
-1

我有一個分析圖像的應用程序。 我必須檢索圖像的拍攝日期。我使用此功能:從位圖獲取EXIF屬性中的拍攝日期

var r = new Regex(":"); 
var myImage = LoadImageNoLock(path); 
{ 
    PropertyItem propItem = null; 
    try 
    { 
     propItem = myImage.GetPropertyItem(36867); 
    } 
    catch{ 
     try 
     { 
      propItem = myImage.GetPropertyItem(306); 
     } 
     catch { } 
    } 
    if (propItem != null) 
    { 
     var dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2); 
     return DateTime.Parse(dateTaken); 
    } 
    else 
    { 
     return null; 
    } 
} 

我的應用程序可以很好地處理相機拍攝的照片。 但現在,我將照片保存從攝像頭這樣的:

private void Webcam_PhotoTakenEvent(Bitmap inImage) 
{ 
    // Save photo on disk 
    if (_takePhoto == true) 
    { 
     // Save the photo on disk 
     inImage.Save(_currentPath + "/BV_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".jpeg"); 
    } 
} 

在這種情況下,我以前的功能不起作用,因爲圖像文件不包含任何PropertyItem。

當我們手動保存圖像時,是否有任何方法可以檢索PropertyItem所採用的日期?

在此先感謝。

+2

filename.Split(「_」)[1]那裏有日期哈哈,反而更嚴重了,如果你自己保存,並進入屬性是日期正確或不日期? – EpicKip

+2

'GetPropertyItem(36867)'得到它我會下注['SetPropertyItem()'](https://msdn.microsoft.com/en-us/library/system.drawing.image.setpropertyitem(v = vs.110 ).aspx)設置它。 –

+0

你是對的@EpicKip,而不是返回null,我可以返回新的FileInfo(路徑).LastWriteTime .. 如果我想在另一個地方移動照片,問題仍然存在。沒有? –

回答

1

最後我找到了Alex的評論。

我手動設置PropertyItem:

private void Webcam_PhotoTakenEvent(Bitmap inImage) 
{ 
    // Set the Date Taken in the EXIF Metadata 
    var newItem = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem)); 
    newItem.Id = 36867; // Taken date 
    newItem.Type = 2; 
    // The format is important the decode the date correctly in the futur 
    newItem.Value = System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss") + "\0"); 
    newItem.Len = newItem.Value.Length; 
    inImage.SetPropertyItem(newItem); 
    // Save the photo on disk 
    inImage.Save(_currentPath + "/BV_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".jpeg"); 
}