/// <exception cref="System.IO.IOException"/> private static void ProcessUrl(Uri url) { URLConnection con = url.OpenConnection(); // con.setConnectTimeout(connectTimeout); // con.setReadTimeout(readTimeout); InputStream @in = con.GetInputStream(); // Read metadata Com.Drew.Metadata.Metadata metadata; try { metadata = ImageMetadataReader.ReadMetadata(@in); } catch (ImageProcessingException e) { // this is an error in the Jpeg segment structure. we're looking for bad handling of // metadata segments. in this case, we didn't even get a segment. System.Console.Error.Printf("%s: %s [Error Extracting Metadata]\n\t%s%n", e.GetType().FullName, url, e.Message); return; } catch (Exception t) { // general, uncaught exception during processing of jpeg segments System.Console.Error.Printf("%s: %s [Error Extracting Metadata]%n", t.GetType().FullName, url); Sharpen.Runtime.PrintStackTrace(t, System.Console.Error); return; } if (metadata.HasErrors()) { System.Console.Error.Println(url); foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { if (!directory.HasErrors()) { continue; } foreach (string error in directory.GetErrors()) { System.Console.Error.Printf("\t[%s] %s%n", directory.GetName(), error); } } } // Iterate through all values foreach (Com.Drew.Metadata.Directory directory_1 in metadata.GetDirectories()) { foreach (Tag tag in directory_1.GetTags()) { string tagName = tag.GetTagName(); string directoryName = directory_1.GetName(); string description = tag.GetDescription(); // truncate the description if it's too long if (description != null && description.Length > 1024) { description = Sharpen.Runtime.Substring(description, 0, 1024) + "..."; } System.Console.Out.Printf("[%s] %s = %s%n", directoryName, tagName, description); } } }
public Task <List <ImageInfo> > GetMetadata(string[] fileNames) { return(Task.Run(() => { List <ImageInfo> imagesInfo = new List <ImageInfo>(); foreach (var file in fileNames) { try { var directories = ImageMetadataReader.ReadMetadata(file); ImageInfo imageInfo = new ImageInfo(); StringBuilder additionalInfo = new StringBuilder(); foreach (var directory in directories) { foreach (var tag in directory.Tags) { switch (tag.Name) { case "Compression Type": imageInfo.CmprssnType = tag.Description; break; case "Compression": imageInfo.CmprssnType = tag.Description; break; case "File Name": imageInfo.FileName = tag.Description; break; case "Image Height": AddPixelSize(imageInfo, tag); break; case "Image Width": AddPixelSize(imageInfo, tag); break; case "X Resolution": imageInfo.Dimension = tag.Description; break; default: additionalInfo.Append($"{tag.Name} = {tag.Description}\n"); break; } } } imageInfo.AdditionalData = additionalInfo.ToString(); imagesInfo.Add(imageInfo); } catch { MessageBox.Show(file); } } return imagesInfo; })); }
public ImageWithExif(String FileName) { this.FileName = FileName; var directories = ImageMetadataReader.ReadMetadata(this.FileName); getTags(directories); }
public Photo(string path) { errorThrown = false; filePath = path; int index = path.LastIndexOf(@"\") + 1; fileName = path.Substring(index); var directories = ImageMetadataReader.ReadMetadata(path); var subInfoDirectories = directories.OfType <MetadataExtractor.Formats.Exif.ExifSubIfdDirectory>(); String time = ""; foreach (var directory in subInfoDirectories) { foreach (MetadataExtractor.Tag tag in directory.Tags) { if (tag.Name == @"Date/Time Original") { time = tag.Description; //2017:05:15 11:53:50 break; } } } if (time == "") { MessageBox.Show(fileName + " could not be loaded." + Environment.NewLine + "No time was found in the Metadata of the photo."); errorThrown = true; } TimeTaken = parseTime(time); /* using (var stream = new FileStream(path, FileMode.Open)) * { * try * { * image = new Bitmap(stream); * } * catch (Exception) * { * MessageBox.Show(fileName + " could not be loaded." + Environment.NewLine + "Bitmap could not be generated from file."); * errorThrown = true; * } * } */ try { image = new Bitmap(new FileStream(path, FileMode.Open)); } catch (Exception) { MessageBox.Show(fileName + " could not be loaded." + Environment.NewLine + "Bitmap could not be generated from file."); errorThrown = true; } }
private static DateTime GetDateTime(string imagePath) { var directories = ImageMetadataReader.ReadMetadata(imagePath); var possibleDates = directories.SelectMany(d => d.Tags).Where(t => t.Name.ToLowerInvariant().Contains("date")); var tag = possibleDates.OrderBy(d => ParseDate(d.Description)).FirstOrDefault(); var possibleDate = ParseDate(tag.Description); return(possibleDate); }
public DateTime ImageMetadataReaderBenchmark() { _stream.Position = 0; var directories = ImageMetadataReader.ReadMetadata(_stream); var subIfdDirectory = directories.OfType <ExifSubIfdDirectory>().First(); return(subIfdDirectory.GetDateTime(ExifDirectoryBase.TagDateTimeOriginal)); }
private PlateSolveResult ExecuteAstap(string Filename) { // Path.Combine(Path.GetDirectoryName(imageFilePath), Path.GetFileNameWithoutExtension(imageFilePath)) + ".ini"; string destinationFile = Path.Combine(Path.GetDirectoryName(Filename), Path.GetFileNameWithoutExtension(Filename)) + ".ini"; string WCSdestinationFile = Path.Combine(Path.GetDirectoryName(Filename), Path.GetFileNameWithoutExtension(Filename)) + ".wcs"; string ASTAP_args; if (File.Exists(destinationFile) && File.Exists(WCSdestinationFile)) { return(ReadAstapOutput(destinationFile)); } double vfov = -1; if (Path.GetExtension(Filename).ToUpper() == ".CR2" || Path.GetExtension(Filename).ToUpper() == ".CR3" || Path.GetExtension(Filename).ToUpper() == ".TIF") { IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(Filename); var subIfdDirectory = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault(); // var dateTime = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagDateTime); try { double focalLen = Convert.ToDouble(Regex.Replace(subIfdDirectory?.GetDescription(ExifDirectoryBase.TagFocalLength), @" mm", "")); if (focalLen != 0) { vfov = 2 * Math.Atan(12 / focalLen); } // 12 is half the height of the 24mm tall sensor vfov = (180 / Math.PI) * vfov; } catch { Console.WriteLine(" Error reading exif from file... "); } } // else if ( Path.GetExtension(Filename) == ".fits" || Path.GetExtension(Filename) == ".fit" ) { // ASTAP_args = GetArguments(Filename, -1, -1, -1); // } ASTAP_args = GetArguments(Filename, -1, -1, vfov); Console.WriteLine("plate solve args: " + ASTAP_args); string executableLocation = @"c:\Program Files\astap\astap.exe"; System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; startInfo.FileName = executableLocation; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; startInfo.Arguments = ASTAP_args; process.StartInfo = startInfo; process.EnableRaisingEvents = true; process.Start(); string result = process.StandardOutput.ReadToEnd(); return(ReadAstapOutput(destinationFile)); }
protected override string?HandleTag(System.IO.FileInfo file) { IEnumerable <Directory> directories = ImageMetadataReader.ReadMetadata(file.FullName); // obtain the Exif SubIFD directory var directory = directories.OfType <TDirectory>().FirstOrDefault(); return(directory?.GetString(_directoryEntryId)); }
public static Position TryExtractPositionFromFile(string file) { Console.WriteLine(file); IReadOnlyList <Directory> directories; try { directories = ImageMetadataReader.ReadMetadata(file); } catch (ImageProcessingException) { Console.WriteLine("Unable to process {0}", file); return(null); } if (!directories.Any()) { return(null); } var latitude = directories.SelectMany(x => x.Tags).FirstOrDefault(t => t.Name == "GPS Latitude"); var longitude = directories.SelectMany(x => x.Tags).FirstOrDefault(t => t.Name == "GPS Longitude"); var date = directories.SelectMany(x => x.Tags).FirstOrDefault(t => t.Name == "GPS Date Stamp"); var time = directories.SelectMany(x => x.Tags).FirstOrDefault(t => t.Name == "GPS Time-Stamp"); var dilutionOfPrecision = directories.SelectMany(x => x.Tags).Where(t => t.Name.StartsWith("GPS DOP")).FirstOrDefault(); // sometimes DOP is represented as rational value (numerator, denominator), sometimes as double. if (latitude != null && longitude != null && date != null && time != null) { var dateTime = $"{date.Description} {time.Description}"; Console.WriteLine(dateTime); Console.WriteLine(gpsFormat); var dateTimeUtc = DateTimeOffset.ParseExact(dateTime, gpsFormat, null, System.Globalization.DateTimeStyles.AssumeUniversal); Console.WriteLine("[{0}]: {1}, {2}", dateTimeUtc, latitude.Description, longitude.Description); return(new Position(dateTimeUtc, LatLongParser.ParseString(latitude.Description), LatLongParser.ParseString(longitude.Description), dilutionOfPrecision == null ? 0.0 : ExifParser.ParseRationalOrDouble(dilutionOfPrecision.Description))); } if (latitude != null && longitude != null) { var filesystemTime = directories.SelectMany(x => x.Tags).FirstOrDefault(t => t.Name == "File Modified Date"); if (filesystemTime != null) { var dateTime = DateTimeOffset.ParseExact(filesystemTime.Description, fileModifiedDateFormat, CultureInfo.InvariantCulture); Console.WriteLine("[{0}]: {1}, {2}", dateTime, latitude.Description, longitude.Description); return(new Position(dateTime, LatLongParser.ParseString(latitude.Description), LatLongParser.ParseString(longitude.Description), PositionUnit.WGS84)); } } return(null); }
private static void TryVideo(IEnumerable <FileInfo> files) { var mp4 = files.FirstOrDefault(f => f.Extension == ".mp4"); using (var stream = mp4.OpenRead()) { var detectFileType = FileTypeDetector.DetectFileType(stream); var directories = ImageMetadataReader.ReadMetadata(stream); } }
public static ExifOrientation GetImageOrientation(string filePath) { // Handle Exif information IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(filePath); var subIfdDirectory = directories.OfType <ExifIfd0Directory>().FirstOrDefault(); var orientation = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagOrientation); Console.WriteLine("Orientation:" + orientation); return(ParseExifDescription(orientation)); }
public FileMetadataContainer GetMetadata(Stream stream) { Guard.NotNull(stream, nameof(stream)); stream.Position = 0; IReadOnlyList <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(stream); return(new MetadataExtractorDirectories(directories)); }
/// <summary> /// Converts a <paramref name="stream"/> of a .dmi to it's metadata string /// </summary> /// <param name="stream">The <see cref="Stream"/> to parse</param> /// <returns>The .dmi metadata string</returns> static string StreamToMetadataString(Stream stream) { var metadata = ImageMetadataReader.ReadMetadata(stream); const string DmiHeader = "# BEGIN DMI"; var description = metadata.SelectMany(x => x.Tags).First(x => x.Description.Contains(DmiHeader)).Description; var startIndex = description.IndexOf(DmiHeader, StringComparison.InvariantCulture) + DmiHeader.Length; var length = description.IndexOf("# END DMI", StringComparison.InvariantCulture) - startIndex; return(description.Substring(startIndex, length)); }
public static void PrintAllMetadata(this string imageFilePath) { foreach (var directory in ImageMetadataReader.ReadMetadata(imageFilePath)) { foreach (var tag in directory.Tags) { Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}"); } } }
protected override void ProcessRecord() { base.ProcessRecord(); WriteVerbose($"Extracting metadata from file: {FilePath}"); var directories = ImageMetadataReader.ReadMetadata(FilePath); WriteObject(directories.SelectMany(GetDirectoryItems).ToList()); }
public PlikGraficzny(Bitmap grafika, string sciezka) { this.grafika = grafika; this.sciezka = sciezka; var directories = ImageMetadataReader.ReadMetadata(sciezka); foreach (var directory in directories) { if (directory.Name == "GPS") { foreach (var tag in directory.Tags) { if (tag.Name == "GPS Longitude") { string wspolrzedne; wspolrzedne = tag.Description; dlugosc = zwrocWspolrzedne(wspolrzedne); } if (tag.Name == "GPS Longitude Ref") { dlugoscKierunek = tag.Description; } if (tag.Name == "GPS Latitude") { string wspolrzedne; wspolrzedne = tag.Description; szerokosc = zwrocWspolrzedne(wspolrzedne); } if (tag.Name == "GPS Latitude Ref") { szerokoscKierunek = tag.Description; } if (tag.Name == "GPS Date Stamp") { string[] pom = tag.Description.Split(':'); dataWykonania = new DateTime(Int32.Parse(pom[0]), Int32.Parse(pom[1]), Int32.Parse(pom[2])); } } } if (directory.Name == "JPEG") { foreach (var tag in directory.Tags) { if (tag.Name == "Image Height") { dlugoscZdjecia = tag.Description.Replace(" pixels", ""); } if (tag.Name == "Image Width") { szerokoscZdjecia = tag.Description.Replace(" pixels", ""); } } } } }
/// <summary> /// 获取图片信息 /// </summary> /// <param name="path"></param> /// <returns></returns> public static PictureInnerInfo GetInnerInfo(string path) { try { var info = new PictureInnerInfo(); var data = ImageMetadataReader.ReadMetadata(path); for (var i = 0; i < data.Count; i++) { if (data[i].Tags == null || data[i].TagCount == 0) { continue; } for (var j = 0; j < data[i].Tags.Count; j++) { var tag = data[i].Tags[j]; if (!tag.HasName) { continue; } if (tag.Name == info.AuthorName) { info.Author = tag.Description?.Replace("\0x0001", "").Replace("\u0001", "").Trim().Substring(0, 32); } else if (tag.Name == info.Tag1Name) { info.Tag1 = tag.Description; } else if (tag.Name == info.Tag2Name) { info.Tag2 = tag.Description; } else if (tag.Name == info.DescriptionName) { info.Description = tag.Description; } else if (tag.Name == info.TakeTimeName) { info.TakeTime = tag.Description; } } } return(info); } catch (Exception) { } return(null); }
//This function is used to extract metadata from each file, and returning it as a string public static string GetMetadata(string file) { string[] ignoredAttributes = { "File Name", "File Size", "File Modified Date", "Detected File Type Name", "Detected File Type Long Name", "Expected File Name Extension" }; string FileType = Path.GetExtension(file); string FileName = Path.GetFileNameWithoutExtension(file); string FileDir = Path.GetDirectoryName(file); FileInfo FileData = new FileInfo(file); long size = FileData.Length; DateTime CreationTime = FileData.CreationTime; DateTime AccessTime = FileData.LastAccessTime; DateTime UpdatedTime = FileData.LastWriteTime; Console.WriteLine(file); //We will catch any exceptions thrown due to incompatibilities of certain files with the ImageMetadataReader //If an exception is thrown, we will just stick to the basic set of attributes already gathered // otherwise, we will gather the extended list of attributes from files that are compatible try{ IEnumerable <MetadataExtractor.Directory> directoriesTest = ImageMetadataReader.ReadMetadata(file); } catch (MetadataExtractor.ImageProcessingException) { //need to figure out a way to get the file owner string fileMetaDataBasic = "FileName:" + FileName + ",FileType:" + FileType + ",Size:" + size + ",Directory:" + FileDir + ",Created:" + CreationTime + ",Accessed:" + AccessTime + ",Updated:" + UpdatedTime; // now we have the basic generic file metadata, we will add extra metadata for each file depending on it's type return(fileMetaDataBasic); } IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(file); foreach (var directory in directories) { foreach (var tag in directory.Tags) { if (!(Array.Exists(ignoredAttributes, element => element == tag.Name))) { if (tag.Name == "Detected MIME Type") { Console.WriteLine("MIME Type:" + tag.Description); } else { Console.WriteLine($"{tag.Name}:{tag.Description}"); } } } } //need to figure out a way to get the file owner string fileMetaData = "FileName:" + FileName + ",FileType:" + FileType + ",Size:" + size + ",Directory:" + FileDir + ",Created:" + CreationTime + ",Accessed:" + AccessTime + ",Updated:" + UpdatedTime; // now we have the basic generic file metadata, we will add extra metadata for each file depending on it's type return(fileMetaData); }
public static async Task AllPhotoMetadataToHtml(FileInfo selectedFile, StatusControlContext statusContext) { await ThreadSwitcher.ResumeBackgroundAsync(); if (selectedFile == null) { statusContext.ToastError("No photo..."); return; } selectedFile.Refresh(); if (!selectedFile.Exists) { statusContext.ToastError($"File {selectedFile.FullName} doesn't exist?"); return; } var photoMetaTags = ImageMetadataReader.ReadMetadata(selectedFile.FullName); var tagHtml = photoMetaTags.SelectMany(x => x.Tags).OrderBy(x => x.DirectoryName).ThenBy(x => x.Name) .ToList().Select(x => new { DataType = x.Type.ToString(), x.DirectoryName, Tag = x.Name, TagValue = ObjectDumper.Dump(x.Description) }).ToHtmlTable(new { @class = "pure-table pure-table-striped" }); var xmpDirectory = ImageMetadataReader.ReadMetadata(selectedFile.FullName).OfType <XmpDirectory>() .FirstOrDefault(); var xmpMetadata = xmpDirectory?.GetXmpProperties().Select(x => new { XmpKey = x.Key, XmpValue = x.Value }) .ToHtmlTable(new { @class = "pure-table pure-table-striped" }); await ThreadSwitcher.ResumeForegroundAsync(); var file = new FileInfo(Path.Combine(UserSettingsUtilities.TempStorageDirectory().FullName, $"PhotoMetadata-{Path.GetFileNameWithoutExtension(selectedFile.Name)}-{DateTime.Now:yyyy-MM-dd---HH-mm-ss}.htm")); var htmlString = ($"<h1>Metadata Report:</h1><h1>{HttpUtility.HtmlEncode(selectedFile.FullName)}</h1><br><h1>Metadata - Part 1</h1><br>" + tagHtml + "<br><br><h1>XMP - Part 2</h1><br>" + xmpMetadata) .ToHtmlDocumentWithPureCss("Photo Metadata", "body {margin: 12px;}"); await File.WriteAllTextAsync(file.FullName, htmlString); var ps = new ProcessStartInfo(file.FullName) { UseShellExecute = true, Verb = "open" }; Process.Start(ps); }
public IReadOnlyList <MetadataExtractor.Directory> GetFileInfo(ApiInstruction apiInstruction) { var filePath = _umbracoContextAccessor.UmbracoContext.HttpContext.Server.MapPath(apiInstruction.ImageUrl); if (File.Exists(filePath)) { var directories = ImageMetadataReader.ReadMetadata(filePath); return(directories); } return(null); }
public void SetFileInformation(string file) { try { _metadataInfo = ImageMetadataReader.ReadMetadata(file).ToList(); } catch (Exception ex) { ConsoleHelper.Error($"Can't read metadata from file {file}. Error: {ex.Message}"); } }
public void ReadFileInfo(string path) { var imageExif = ImageMetadataReader.ReadMetadata(path); labFileName.Text = imageExif[9].Tags[0].Description; labDate.Text = imageExif[9].Tags[2].Description; labFileSize.Text = Math.Round(float.Parse(imageExif[9].Tags[1].Description.Split(' ')[0]) / 1024 / 1024, 2) + " MB"; labImageSize.Text = imageExif[0].Tags[3].Description.Split(' ')[0] + " x " + imageExif[0].Tags[2].Description.Split(' ')[0]; labShot.Text = imageExif[2].Tags[0].Description + " " + imageExif[2].Tags[1].Description + " " + imageExif[3].Tags[24].Description.Split(' ')[0]; labISO.Text = imageExif[2].Tags[3].Description; labDevice.Text = imageExif[1].Tags[1].Description; }
private static DateTime GetImageDate(string name) { var directories = ImageMetadataReader.ReadMetadata(name); var exifSubDirectory = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault(); var originalDate = exifSubDirectory?.GetDescription(ExifDirectoryBase.TagDateTimeOriginal); var date = DateTime.TryParseExact(originalDate, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out var tempDate) ? tempDate : DateTime.Now; return(date); }
private static void MetadataTest() { IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata("Data/DSC05338.ARW"); foreach (var directory in directories) { foreach (var tag in directory.Tags) { Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}"); } } }
private void _watcher_Created(object sender, FileSystemEventArgs e) { _logger.LogInformation($"{e.Name}: {e.ChangeType}"); WaitForFile(e.FullPath); var directories = ImageMetadataReader.ReadMetadata(e.FullPath); foreach (var directory in directories) { foreach (var tag in directory.Tags) { _logger.LogDebug($"{e.Name}:{directory.Name} - {tag.Name} = {tag.Description}"); } } var imageInfo = new ImageInfo(); var exifIfd0Directory = directories.OfType <ExifIfd0Directory>().FirstOrDefault(); if (exifIfd0Directory != null) { imageInfo.CaptureDate = exifIfd0Directory.GetDateTime(ExifDirectoryBase.TagDateTime); imageInfo.Camera = exifIfd0Directory.GetString(ExifDirectoryBase.TagModel); imageInfo.Width = exifIfd0Directory.TryGetInt32(ExifSubIfdDirectory.TagImageWidth, out var Width) ? Width : 0; imageInfo.Height = exifIfd0Directory.TryGetInt32(ExifSubIfdDirectory.TagImageHeight, out var Height) ? Height : 0; } var exifSubIfdDirectory = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault(); if (exifSubIfdDirectory != null) { imageInfo.ExposureTime = exifSubIfdDirectory.TryGetDouble(ExifSubIfdDirectory.TagExposureTime, out var exposureTimer) ? exposureTimer : Double.NaN; imageInfo.FNumber = exifSubIfdDirectory.TryGetDouble(ExifSubIfdDirectory.TagFNumber, out var fnumber) ? fnumber : Double.NaN; imageInfo.FocalLength35 = exifSubIfdDirectory.TryGetDouble(ExifSubIfdDirectory.TagFNumber, out var focalLength35) ? focalLength35 : Double.NaN; imageInfo.FocalLength = exifSubIfdDirectory.TryGetDouble(ExifSubIfdDirectory.TagFNumber, out var focalLength) ? focalLength : Double.NaN; imageInfo.LensModel = exifSubIfdDirectory.GetString(ExifSubIfdDirectory.TagLensModel); } var gpsInfo = directories.OfType <GpsDirectory>().FirstOrDefault(); if (gpsInfo != null) { if ( gpsInfo.TryGetDouble(GpsDirectory.TagLatitude, out var latitude) && gpsInfo.TryGetDouble(GpsDirectory.TagLongitude, out var longitude)) { imageInfo.GpsInfo = new Position(longitude, latitude); } } _logger.LogInformation($"{e.Name}: Done"); }
public Metadata(string filepath) { //Metadata Extractor handles metadata formats //Exif IPTC XMP JFIF JFXX ICC 8BIM //file extentions //JPEG PNG WebP GIF ICO BMP TIFF PSD PCX RAW CRW CR2 NEF ORF RAF RW2 RWL SRW ARW DNG X3F //MOV MP4 M4V 3G2 3GP 3GP //MP3 WAV //Manufacturer makernote support //Agfa Canon Casio Epson Fujifilm Foveon Kodak Kyocera Nikon Minolta Olympus Panasonic Pentax Sigma Sony directories = ImageMetadataReader.ReadMetadata(filepath); }
private static string ExtractDateTimeFromMetadata(string file) { try { IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(file); return(FindDateTimeFromDirectories(directories, out var dateTime) ? dateTime.Trim() : null); } catch (Exception e) { return(null); } }
public DateTime?BuildFromMetaData(string sourceFile) { var metaData = ImageMetadataReader.ReadMetadata(sourceFile); var dateTimes = new [] { Get <ExifIfd0Directory>(metaData, ExifDirectoryBase.TagDateTime), Get <ExifSubIfdDirectory>(metaData, ExifDirectoryBase.TagDateTimeOriginal), Get <ExifSubIfdDirectory>(metaData, ExifDirectoryBase.TagDateTimeDigitized), Get <ExifSubIfdDirectory>(metaData, ExifDirectoryBase.TagDateTime), Get <QuickTimeMovieHeaderDirectory>(metaData, QuickTimeMovieHeaderDirectory.TagCreated), Get <FileMetadataDirectory>(metaData, FileMetadataDirectory.TagFileModifiedDate) }; if (dateTimes.Length > 1) { } var orderedDateTimes = dateTimes .Where(dt => dt.HasValue) .Select(dt => dt.Value) .Select(dt => dt.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(dt, DateTimeKind.Utc).ToLocalTime() : dt) // Unspecified times are utc times. .OrderBy(dt => dt.Date) .ToArray(); return(orderedDateTimes.FirstOrDefault()); // var exIfMetaData = metaData?.OfType<ExifSubIfdDirectory>().FirstOrDefault(); // if (exIfMetaData != null) // { // if(exIfMetaData.TryGetDateTime(ExifDirectoryBase.TagDateTimeOriginal, out var dateTimeOriginal)) // { // return dateTimeOriginal; // }; // if(exIfMetaData.TryGetDateTime(ExifDirectoryBase.TagDateTimeDigitized, out var dateTimeDigitized)) // { // return dateTimeDigitized; // }; // if(exIfMetaData.TryGetDateTime(ExifDirectoryBase.TagDateTime, out var dateTime)) // { // return dateTime; // }; // } // // var quickTimeMetaData = metaData?.OfType<QuickTimeMovieHeaderDirectory>().FirstOrDefault(); // if (quickTimeMetaData != null) // { // if(quickTimeMetaData.TryGetDateTime(QuickTimeMovieHeaderDirectory.TagCreated, out var dateTimeCreated)) // { // return dateTimeCreated; // }; // } // return null; }
public DateTime GetImageData(string path) { try { if (!File.Exists(path)) { throw new FileNotFoundException($"File cannot be found by path: {path}"); } var metadata = ImageMetadataReader.ReadMetadata(path); var ifd0Directory = metadata.OfType <ExifIfd0Directory>().FirstOrDefault(); if (ifd0Directory != null && !string.IsNullOrEmpty(ifd0Directory.GetDescription(ExifDirectoryBase.TagDateTime))) { var dateTimeString = ifd0Directory.GetDescription(ExifDirectoryBase.TagDateTime); var model = ifd0Directory.GetDescription(ExifDirectoryBase.TagModel); if (string.IsNullOrEmpty(dateTimeString)) { throw new FileLoadException("Date taken value is not defined in EXIF IFD0 of the file"); } if (string.IsNullOrEmpty(model)) { throw new FileLoadException("Camera model value is not defined in EXIF IFD0 of the file"); } var dateTimeRegexPattern = @"\d{4}:\d{2}:\d{2} \d{2}:\d{2}:\d{2}"; if (!Regex.IsMatch(dateTimeString, dateTimeRegexPattern)) { throw new FileLoadException($"Date taken value is converted in wrong format. Expected: '{dateTimeRegexPattern}', but was: '{dateTimeString}'."); } var splitDateTimeStr = dateTimeString.Split(' '); var date = DateTime.ParseExact(splitDateTimeStr[0], "yyyy:MM:dd", CultureInfo.CurrentCulture); var splitTime = splitDateTimeStr[1].Split(':'); var time = new TimeSpan(Convert.ToInt32(splitTime[0]), Convert.ToInt32(splitTime[1]), Convert.ToInt32(splitTime[2])); var dateTime = new DateTime(date.Year, date.Month, date.Day, time.Hours, time.Minutes, time.Seconds); return(dateTime); } var fileInfo = new FileInfo(path); return(fileInfo.LastWriteTime); } catch (Exception e) { ConsoleHelper.WriteLine($"\tException occurred for file:\r\n\t{path}", ConsoleColor.Red); ConsoleHelper.WriteLine($"\t{e.Message}", ConsoleColor.Red); ConsoleHelper.WriteLine(); return(default);
internal void Run() { Console.WriteLine("Please Enter the path:"); var directoryPath = Console.ReadLine(); if (string.IsNullOrWhiteSpace(directoryPath) || !Directory.Exists(directoryPath)) { return; } var paths = Directory.GetFiles(directoryPath).ToList(); var unchangedFiles = new List <(string fileName, string message)>(); var count = 0; foreach (var path in paths.Where(path => Path.GetExtension(path) != ".ini")) { IReadOnlyList <MetadataExtractor.Directory>?directories; try { directories = ImageMetadataReader.ReadMetadata(path); } catch (ImageProcessingException) { WriteWarning("Couldn't find file metadata"); directories = null; } var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path); // if (IsStringFitsCorrectDateFormat(fileNameWithoutExtension, out _)) // { // continue; // } var formattedDate = GetFormattedDate(directories, path); if (formattedDate == null) { WriteError($"File {fileNameWithoutExtension} doesn't contain correct information about date in its tags"); continue; } if (!IsStringFitsCorrectDateFormat(formattedDate, out _)) { WriteError($"File {fileNameWithoutExtension} contains the wrong information in date taken tag"); continue; } count += Rename(path, formattedDate); } Console.WriteLine($"Total number of files in folder: {paths.Count}. Converted: {count}"); unchangedFiles.ForEach(f => Console.WriteLine($"{f.fileName}: {f.message}")); }