Beispiel #1
0
        /* it uses the metadata-extractor package to read the required exif data from the image */
        private void ReadExif(string photoPath)
        {
            _exif = new Dictionary <string, double>()
            {
                { "ExposureTime", Double.NaN }, { "Iso", Double.NaN }, { "F-number", Double.NaN }
            };

            IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(photoPath);

            var subIfdDirectory = directories.OfType <ExifSubIfdDirectory>().Where(s => s.ContainsTag(ExifDirectoryBase.TagFNumber)).FirstOrDefault();

            _exif["Iso"] = int.Parse(subIfdDirectory?.GetDescription(ExifDirectoryBase.TagIsoEquivalent));
            string expression = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagExposureTime).Split(' ')[0];

            if (expression.Contains('/'))
            {
                double num = Double.Parse(expression.Split('/')[0]);
                double den = Double.Parse(expression.Split('/')[1]);
                _exif["ExposureTime"] = (num / den);
            }
            else
            {
                _exif["ExposureTime"] = Double.Parse(expression);
            }

            _exif["F-number"] = double.Parse(subIfdDirectory?.GetDescription(ExifDirectoryBase.TagFNumber).Substring(2));
        }
Beispiel #2
0
    public ImageMedia(string path) : base(path)
    {
        IEnumerable <Directory> directories = ImageMetadataReader.ReadMetadata(path);

        foreach (var directory in directories)
        {
            foreach (var tag in directory.Tags)
            {
                ///System.Diagnostics.Debug.WriteLine($"[{directory.Name}] {tag.Name} = {tag.Description}");
                switch (tag.Name)
                {
                case "Image Width":
                    width = tag.Description;
                    break;

                case "Image Height":
                    height = tag.Description;
                    break;
                }
            }

            if (directory.HasError)
            {
                foreach (var error in directory.Errors)
                {
                    System.Diagnostics.Debug.WriteLine($"ERROR: {error}");
                }
            }
        }
    }
Beispiel #3
0
    private DateTime GetDateTaken()
    {
        try
        {
            DateTime date = new DateTime();
            IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(SourcePath);

            foreach (MetadataExtractor.Directory directory in directories)
            {
                if (directory.TryGetDateTime(ExifDirectoryBase.TagDateTimeOriginal, out date))
                {
                    return(date);
                }
            }

            foreach (MetadataExtractor.Directory directory in directories)
            {
                if (directory.TryGetDateTime(ExifDirectoryBase.TagDateTime, out date))
                {
                    return(date);
                }
            }
        }
        catch (Exception) { }

        return(FileDate);
    }
Beispiel #4
0
        private void ReadExif()
        {
            IEnumerable <Directory> directories = ImageMetadataReader.ReadMetadata(this.path);
            var subIfdDirectory  = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault();
            var mainIfdDirectory = directories.OfType <ExifIfd0Directory>().FirstOrDefault();

            try
            {
                this.dateTaken    = Convert.ToDateTime(mainIfdDirectory.GetDescription(ExifDirectoryBase.TagDateTime));
                this.manufacturer = mainIfdDirectory.GetDescription(ExifDirectoryBase.TagMake);
                this.model        = mainIfdDirectory.GetDescription(ExifDirectoryBase.TagModel);

                this.iso          = Convert.ToInt32(subIfdDirectory?.GetDescription(ExifDirectoryBase.TagIsoEquivalent));
                this.fStop        = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagFnumber);
                this.exposureTime = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagExposureTime);
                this.program      = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagExposureProgram);
                this.metering     = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagMeteringMode);
                this.flashMode    = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagFlash);
                string tempFocal = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagFocalLength);
                this.focalLength = Convert.ToInt32(tempFocal.Substring(0, tempFocal.Length - 3));
                this.valid       = true;
            }
            catch
            {
                this.valid = false;
                return;
            }
        }
        public async Task <Photo[]> ReadAllFromDir(PhotoLoadType loadType = PhotoLoadType.Miniature, bool isRecursive = false)
        {
            var dig = new OpenFileDialog()
            {
                //TODO: Multi language support
                Title = "Chose directory image files"
            };
            var multipleFiles = await _reader.ReadAllFromDir(dig, isRecursive);

            var photoList = new List <Photo>();

            foreach (var(path, stream) in multipleFiles)
            {
                try
                {
                    var imageBrush          = ReadImageBrushFromFile(stream, loadType);
                    var metaDataDirectories = ImageMetadataReader.ReadMetadata(stream);
                    var photo = new Photo
                    {
                        ImageBrush          = imageBrush,
                        Attribute           = Attribute.NotProcessed,
                        Caption             = GetCaptionFromPath(path),
                        MetaDataDirectories = metaDataDirectories
                    };
                    photoList.Add(photo);
                }
                catch (Exception e)
                {
                    throw new Exception($"unable to read image from {path}");
                }
            }
            return(photoList.ToArray());
        }
        public void ReadFileInfo(string path)
        {
            var imageExif = ImageMetadataReader.ReadMetadata(path);

            labFileName.Text      = imageExif[9].Tags[0].Description;
            labFileName.BackColor = Color.Transparent;
        }
        public async Task <Photo[]> ReadAllFromDir(PhotoLoadType loadType = PhotoLoadType.Miniature, bool isRecursive = false)
        {
            var dig = new OpenFolderDialog()
            {
                //TODO: Multi language support
                Title = "Chose directory image files"
            };
            var multipleFiles = await _reader.ReadAllFromDir(dig, isRecursive);

            var photoList = new List <Photo>();

            foreach (var(path, stream) in multipleFiles)
            {
                try
                {
                    var imageBrush          = ReadImageBrushFromFile(stream, loadType);
                    var metaDataDirectories = ImageMetadataReader.ReadMetadata(path);
                    var photo = new Photo
                    {
                        ImageBrush          = imageBrush,
                        Attribute           = Attribute.NotProcessed,
                        MetaDataDirectories = metaDataDirectories
                    };
                    photoList.Add(photo);
                }
                catch (Exception e)
                {
                    //TODO: translate to rus
                    Console.WriteLine($"ERROR: image from {path} is skipped!\nDetails: {e}");
                }
            }
            return(photoList.ToArray());
        }
Beispiel #8
0
 private void ReadMetadata()
 {
     try
     {
         ExifTags.Clear();
         if (CurrentPicture != null)
         {
             ExifTags.Add("=== METADATA ===");
             IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(CurrentPicture.Path);
             foreach (var directory in directories)
             {
                 foreach (var tag in directory.Tags)
                 {
                     ExifTags.Add(directory.Name + " - " + tag.Name + " = " + tag.Description);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error por asginación nula en CurrentPicture: " + ex.ToString());
     }
     finally
     {
         RaisePropertyChanged("ExifTags");
     }
 }
        public bool LoadData(string path)
        {
            Path = path;
            IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(path);
            var exifDirectory = directories.OfType <MetadataExtractor.Formats.Exif.ExifIfd0Directory>().FirstOrDefault();
            var gpsDirectory  = directories.OfType <MetadataExtractor.Formats.Exif.GpsDirectory>().FirstOrDefault();
            var fileDirecory  = directories.OfType <MetadataExtractor.Formats.FileSystem.FileMetadataDirectory>().FirstOrDefault();

            HasGPS = gpsDirectory != null;
            if (exifDirectory != null)
            {
                IsRAW = RawFiles.Contains(System.IO.Path.GetExtension(path).ToLower());

                Make     = exifDirectory.GetString(271);
                ShotTime = exifDirectory.GetDateTime(306);
                Model    = exifDirectory.GetString(272);
            }

            if (fileDirecory != null)
            {
                FileSize = fileDirecory.GetInt64(2);
            }

            return(true);
        }
Beispiel #10
0
        private void ouvrirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ofdFile.ShowDialog() == DialogResult.OK)
            {
                Console.WriteLine(ofdFile.FileName);
                Console.WriteLine(Path.GetExtension(ofdFile.FileName));

                Bitmap img;

                if (Path.GetExtension(ofdFile.FileName) == ".webp")
                {
                    WebP webp = new WebP();
                    img = webp.Load(ofdFile.FileName);
                }
                else
                {
                    img = new Bitmap(ofdFile.FileName);
                }
                pibImg.Image = img;

                lsbMetadata.Items.Clear();

                IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(ofdFile.FileName);
                foreach (var dir in directories)
                {
                    foreach (var item in dir.Tags)
                    {
                        Console.WriteLine(item);
                        lsbMetadata.Items.Add(item);
                    }
                }
            }
        }
Beispiel #11
0
 /// <summary>
 /// Parses the metadata, writing error information to the console if it failes.
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 static Com.Drew.Metadata.Metadata  ParseMetadata(Stream data, string info)
 {
     try
     {
         if (!data.CanSeek)
         {
             var ms = new MemoryStream(4096);//We have to guess at length, can't seek
             data.CopyTo(ms);
             ms.Seek(0, SeekOrigin.Begin);
             return(ImageMetadataReader.ReadMetadata(InputStream.Wrap(ms)));
         }
         return(ImageMetadataReader.ReadMetadata(InputStream.Wrap(data)));
     }
     catch (ImageProcessingException e)
     {
         Console.ForegroundColor = ConsoleColor.Red;
         // 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.
         Console.Error.WriteLine("{0}: {1} [Error Extracting Metadata]\n\t{2}\n", e.GetType().FullName, info, e.Message);
         return(null);
     }
     catch (Exception t)
     {
         Console.ForegroundColor = ConsoleColor.Red;
         // general, uncaught exception during processing of jpeg segments
         Console.Error.WriteLine("{0}: {1} [Error Extracting Metadata]\n", t.GetType().FullName, info);
         Console.Error.WriteLine(t);
         return(null);
     }
 }
Beispiel #12
0
    /// <summary>
    /// Read the metadata, and handle any exceptions.
    /// </summary>
    /// <param name="imagePath"></param>
    /// <returns>Metadata, or Null if there was an error</returns>
    private IReadOnlyList <MetadataExtractor.Directory> SafeReadImageMetadata(string imagePath)
    {
        var watch = new Stopwatch("ReadMetaData");

        IReadOnlyList <MetadataExtractor.Directory> metadata = null;

        if (File.Exists(imagePath))
        {
            try
            {
                metadata = ImageMetadataReader.ReadMetadata(imagePath);
            }
            catch (ImageProcessingException ex)
            {
                Logging.Log("Metadata read for image {0}: {1}", imagePath, ex.Message);
            }
            catch (IOException ex)
            {
                Logging.Log("File error reading metadata for {0}: {1}", imagePath, ex.Message);
            }
        }

        watch.Stop();

        return(metadata);
    }
        public ImageModel CreateImageFromByteArray(byte[] bytes)
        {
            var directories     = ImageMetadataReader.ReadMetadata(new MemoryStream(bytes));
            var subIfdDirectory = directories.OfType <GpsDirectory>().FirstOrDefault();
            var latitudeDeg     = subIfdDirectory?.GetDescription(GpsDirectory.TagLatitude);
            var longitudeDeg    = subIfdDirectory?.GetDescription(GpsDirectory.TagLongitude);

            string latitude  = null;
            string longitude = null;


            if (latitudeDeg != null && longitudeDeg != null)
            {
                latitude  = ConvertToDecimal(latitudeDeg);
                longitude = ConvertToDecimal(longitudeDeg);
            }

            Guid id = Guid.NewGuid();

            ImageModel imageModel = new ImageModel()
            {
                ImageId   = id.ToString(),
                Latitude  = latitude,
                Longitude = longitude,
                PostDate  = DateTime.Now
            };

            return(imageModel);
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            //const string filePath = @"E:\metadata-extractor-dotnet-2.2.0\MetadataExtractor.Console\Data\withIptcExifGps.jpg";
            const string filePath = @"K:\metadata-extractor-2.2.0\MetadataExtractor.Console\Resources\1.MOV";

            //const string filePath = @"K:\metadata-extractor-2.2.0\MetadataExtractor.Console\Resources\1.JPG";
            System.Console.WriteLine($"Processing file: {filePath}");

            // There are multiple ways to get a Metadata object for a file

            //
            // SCENARIO 1: UNKNOWN FILE TYPE
            //
            // This is the most generic approach.  It will transparently determine the file type and invoke the appropriate
            // readers.  In most cases, this is the most appropriate usage.  This will handle JPEG, TIFF, GIF, BMP and RAW
            // (CRW/CR2/NEF/RW2/ORF) files and extract whatever metadata is available and understood.
            //
            try
            {
                var directories = ImageMetadataReader.ReadMetadata(filePath);

                Print(directories, "Using ImageMetadataReader");
            }
            catch (ImageProcessingException e)
            {
                PrintError(e);
            }
            catch (IOException e)
            {
                PrintError(e);
            }
Beispiel #15
0
        static void Main()
        {
            string path = "Q:\\XXX\\ZZ\\201014 众\\2020.10.14_104356.mov";

            var directories = ImageMetadataReader.ReadMetadata(path);

            FileSystemInfo file = new FileInfo(path);
            var            mi   = new MediaInfo();

            mi.Open(file.FullName);
            Console.WriteLine(mi.Inform());
            mi.Close();
            mi.Dispose();

            foreach (var directory in directories)
            {
                foreach (var tag in directory.Tags)
                {
                    Console.WriteLine($"[{directory.Name}] {tag.Name} = {tag.Description}");
                }

                if (directory.HasError)
                {
                    foreach (var error in directory.Errors)
                    {
                        Console.WriteLine($"ERROR: {error}");
                    }
                }
            }

            Console.ReadKey();
        }
Beispiel #16
0
        private void AnalyzeFiles(object sender, DoWorkEventArgs e)
        {
            Result = new List <PhotoMetadataModel>();

            foreach (var imageFile in _imageFiles)
            {
                if (Worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                var newMetadata = new PhotoMetadataModel();
                newMetadata.FileName = imageFile;

                try
                {
                    var metadata = ImageMetadataReader.ReadMetadata(imageFile);

                    ReadGpsInformation(newMetadata, metadata);
                    ReadSubIfInformation(newMetadata, metadata);
                }
                catch (Exception ex)
                {
                    newMetadata.AnalysisErrors.Add($"Unable to read file: {ex.Message}");
                }

                Result.Add(newMetadata);
                ImageFilesProcessed++;
                var percentCompleted = (int)(ImageFilesProcessed / ImageFileCount) * 100;
                Worker.ReportProgress(percentCompleted, newMetadata);
            }
        }
Beispiel #17
0
        public ImageSource GetThumbnail(String filepath)
        {
            // atm: thumbnails are not freed

            ImageSource img = null;

            try
            {
                using (var fstream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096))
                {
                    var dirs = ImageMetadataReader.ReadMetadata(fstream);
                    img = ReadThumbnailFromExif(filepath, dirs.OfType <ExifThumbnailDirectory>().FirstOrDefault());
                }
            } catch (Exception e)
            {
                // TODO: log exception
                img = null;
            }

            if (img == null)
            {
                // there is no embedded thumbnail -> generate one
                var c = new CachedImage(filepath, 80);
                c.Load();
                img = c.ImageSource;
            }

            return(img);
        }
		static void Main(string[] args)
		{
			//RegisterNamespaceTest();

			PrintSchemaRegistry();
			Console.WriteLine();

			foreach (var filePath in args)
			{
				if (File.Exists(filePath))
				{
					Console.WriteLine($"\"{filePath}\":");
					//XmpMetaFactory.Reset(); // calling Reset() fixes the issue with Namespaces and Path being "MicrosoftPhoto:Rating" or "MicrosoftPhoto_1_:Rating", but Reset() should not be called as per the documentation ...
					var metadataDirectories = ImageMetadataReader.ReadMetadata(filePath);
					var xmpDirectory = metadataDirectories.OfType<XmpDirectory>().FirstOrDefault();
					foreach (var property in xmpDirectory.XmpMeta.Properties)
					{
						if (((property.Path != null) && property.Path.Contains("microsoft" /*"MicrosoftPhoto"*/, StringComparison.OrdinalIgnoreCase)) ||
						    ((property.Namespace != null) && property.Namespace.Contains("microsoft" /*"ns.microsoft.com/photo/1.0"*/, StringComparison.OrdinalIgnoreCase)))
						{
							Console.WriteLine($"  XMP: path={property.Path} => value={property.Value}, namespace={property.Namespace}");
						}
					}
					PrintSchemaRegistry();
				}
				else
				{
					Console.WriteLine($"ERROR: file \"{filePath}\" not found");
				}
				Console.WriteLine();
			}
		}
Beispiel #19
0
        private void setImageListView(string[] filelist)
        {
            //detailView.Clear();
            foreach (string objFile in filelist)
            {
                // Exif Format을 가진 이미지파일만 작업 수행
                if (Tourist.TouristBasicUtil.checkExifFile(objFile))
                {
                    Tourist.PropertyFileInfo pf = Tourist.TouristFileInfo.getFileInfo(objFile);
                    FileListView = new ListViewItem(pf.filename);
                    FileListView.SubItems.Add("test");
                    FileListView.SubItems.Add(Tourist.TouristBasicUtil.GetFileSize(pf.filesize));
                    detailView.Items.Add(FileListView);
                    FileStream fs = new FileStream(objFile, FileMode.Open, FileAccess.Read);
                    IEnumerable <MetadataExtractor.Directory> directories = ImageMetadataReader.ReadMetadata(fs);
                    var    subIfdDirectory = directories.OfType <MetadataExtractor.Formats.Exif.GpsDirectory>().FirstOrDefault();
                    var    gpsLatitude     = subIfdDirectory?.GetDescription(MetadataExtractor.Formats.Exif.GpsDirectory.TagLatitude);
                    var    gpsLongitude    = subIfdDirectory?.GetDescription(MetadataExtractor.Formats.Exif.GpsDirectory.TagLongitude);
                    double Latitude        = Tourist.TouristBasicUtil.ConvertGPSLocation(subIfdDirectory?.GetDescription(MetadataExtractor.Formats.Exif.GpsDirectory.TagLatitude));
                    double Longitude       = Tourist.TouristBasicUtil.ConvertGPSLocation(subIfdDirectory?.GetDescription(MetadataExtractor.Formats.Exif.GpsDirectory.TagLongitude));

                    TouristGmap.Overlays.Add(SetMarkers(Latitude, Longitude));
                }
                detailView.EndUpdate();
                if (detailView.Items.Count == 0)
                {
                    detailViewLabel.Visible = true;
                }
                else
                {
                    detailViewLabel.Visible = false;
                }
            }
        }
Beispiel #20
0
        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.CompressionType = tag.Description;
                                    break;

                                case "Compression":
                                    imageInfo.CompressionType = 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 Dictionary <string, Dictionary <string, string> > getExif(Stream fileStream)
        {
            Dictionary <string, Dictionary <string, string> > exif = new Dictionary <string, Dictionary <string, string> >();

            try
            {
                if (fileStream.CanSeek)
                {
                    foreach (MetadataExtractor.Directory d in ImageMetadataReader.ReadMetadata(fileStream).ToList())
                    {
                        Dictionary <string, string> tmp = new Dictionary <string, string>();
                        foreach (MetadataExtractor.Tag t in d.Tags)
                        {
                            tmp.Add(t.Name, t.Description);
                        }
                        exif.Add(d.Name, tmp);
                    }
                    return(exif);
                }
                else
                {
                    return(exif);
                }
            }
            catch
            {
                return(exif);
            }
        }
        public async Task <IActionResult> New(PhotosViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = UploadedFile(model);
                var    photoPath      = "wwwroot/images/" + uniqueFileName;
                var    gps            = ImageMetadataReader.ReadMetadata(photoPath)
                                        .OfType <GpsDirectory>()
                                        .FirstOrDefault();
                var    location        = gps.GetGeoLocation();
                var    photoLat        = location.Latitude;
                var    photoLong       = location.Longitude;
                var    directories     = ImageMetadataReader.ReadMetadata(photoPath);
                var    subIfdDirectory = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault();
                var    photoDate       = subIfdDirectory?.GetDescription(ExifDirectoryBase.TagDateTimeOriginal);
                Photos photo           = new Photos
                {
                    PhotoFile    = uniqueFileName,
                    PhotoTripId  = model.PhotoTripId,
                    PhotoCaption = model.PhotoCaption,
                    PhotoLat     = photoLat.ToString(),
                    PhotoLong    = photoLong.ToString(),
                    PhotoDate    = photoDate
                };
                _context.Add(photo);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View());
        }
        public async Task <Photo> Read(PhotoLoadType loadType = PhotoLoadType.Miniature)
        {
            var dig = new OpenFileDialog()
            {
                //TODO: Multi language support
                Title = "Chose the image file"
            };

            var(path, stream) = await _reader.Read(dig);

            try
            {
                var imageBrush          = ReadImageBrushFromFile(stream, loadType);
                var metaDataDirectories = ImageMetadataReader.ReadMetadata(stream);
                var photo = new Photo
                {
                    ImageBrush          = imageBrush,
                    Attribute           = Attribute.NotProcessed,
                    Caption             = GetCaptionFromPath(path),
                    MetaDataDirectories = metaDataDirectories
                };
                return(photo);
            }
            catch (Exception e)
            {
                throw new Exception($"unable to read image from {path}");
            }
        }
Beispiel #24
0
        public Photo Load(string source, PhotoLoadType loadType)
        {
            var loader = new FileLoader();

            using (var stream = loader.Load(source))
            {
                try
                {
                    var imageBrush          = ReadImageBrushFromFile(stream, loadType);
                    var metaDataDirectories = ImageMetadataReader.ReadMetadata(stream);
                    var photo = new Photo
                    {
                        ImageBrush          = imageBrush,
                        Attribute           = Attribute.NotProcessed,
                        Caption             = GetCaptionFromPath(source),
                        MetaDataDirectories = metaDataDirectories
                    };
                    return(photo);
                }
                catch (Exception e)
                {
                    throw new Exception($"unable to load image from {source}", e);
                }
            }
        }
Beispiel #25
0
        private static void ProcessDirectory([NotNull] string path, [NotNull] IFileHandler handler, [NotNull] string relativePath, [NotNull] TextWriter log)
        {
            var entries = System.IO.Directory.GetFileSystemEntries(path);

            // Order alphabetically so that output is stable across invocations
            Array.Sort(entries, string.CompareOrdinal);

            foreach (var entry in entries)
            {
                var file = Path.Combine(path, entry);

                if (System.IO.Directory.Exists(file))
                {
                    ProcessDirectory(file, handler, relativePath.Length == 0 ? entry : relativePath + "/" + entry, log);
                }
                else if (handler.ShouldProcess(file))
                {
                    handler.OnBeforeExtraction(file, relativePath, log);

                    // Read metadata
                    try
                    {
                        var directories = ImageMetadataReader.ReadMetadata(file);
                        handler.OnExtractionSuccess(file, directories, relativePath, log);
                    }
                    catch (Exception e)
                    {
                        handler.OnExtractionError(file, e, log);
                    }
                }
            }
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            try
            {
                var gps = ImageMetadataReader.ReadMetadata(args[0])
                          .OfType <GpsDirectory>()
                          .FirstOrDefault();

                var location = gps.GetGeoLocation();

                string GPS      = location.Latitude.ToString().Replace(',', '.') + "," + location.Longitude.ToString().Replace(',', '.');
                string GPS_LINK = "http://maps.google.de/maps?q=" + GPS;


                System.Diagnostics.Process.Start(GPS_LINK);
                var t = new Thread((ThreadStart)(() =>
                {
                    System.Windows.Forms.Clipboard.SetText(GPS);
                }));

                t.SetApartmentState(ApartmentState.STA);

                t.Start();

                t.Join();
            }
            catch (Exception e)
            {
                Console.ReadKey();
            }
        }
Beispiel #27
0
        private CameraInfo GetCamera(Stream stream)
        {
            try
            {
                var metadata = ImageMetadataReader.ReadMetadata(stream);
                if (metadata.Count == 0)
                {
                    return(null);
                }

                return(new CameraInfo
                {
                    Base = GetBase(metadata),
                    Canon = GetCanon(metadata),
                });
            }
            catch (MetadataException ex)
            {
                Logger.LogError(0, ex, "Error reading metadata");
                throw new CameraDetectionException(ex);
            }
            catch (ImageProcessingException ex)
            {
                Logger.LogError(0, ex, "Error processing metadata");
                throw new CameraDetectionException(ex);
            }
        }
        static void Main(string[] args)
        {
            var image       = File.OpenRead(@"images\smith-river.JPG");
            var directories = ImageMetadataReader.ReadMetadata(image);

            foreach (var dir in directories.Where(x => x.Name == "GPS"))
            {
                Console.WriteLine(dir);

                var dic       = dir.Tags.ToDictionary(x => x.Name, x => x.Description);
                var latKey    = "GPS Latitude";
                var latRefKey = "GPS Latitude Ref";

                var lonKey    = "GPS Longitude";
                var lonRefKey = "GPS Longitude Ref";

                var utcKey = "GPS Time-Stamp";

                var lat    = dic[latKey];
                var latRef = dic[latRefKey];

                var lon    = dic[lonKey];
                var lonRef = dic[lonRefKey];
                var utc    = dic[utcKey];

                var y = $"{lat} {latRef},{lon} {lonRef}";
                var coodWithString = Coordinate.fromDegreeMinuteSecondString(y).ToString();

                Console.WriteLine($"https://maps.googleapis.com/maps/api/geocode/json?latlng={coodWithString}&key={API_KEY}");
            }

            Console.ReadKey();
        }
Beispiel #29
0
        private static void ProcessDirectory([NotNull] string path, [NotNull] IFileHandler handler, [NotNull] string relativePath, [NotNull] TextWriter log)
        {
            var entries = System.IO.Directory.GetFileSystemEntries(path);

            // Order alphabetically so that output is stable across invocations
            Array.Sort(entries, string.CompareOrdinal);

            foreach (var entry in entries)
            {
                var file = Path.Combine(path, entry);

                if (System.IO.Directory.Exists(file))
                {
                    ProcessDirectory(file, handler, relativePath.Length == 0 ? new DirectoryInfo(entry).Name : relativePath + "/" + new DirectoryInfo(entry).Name, log);
                }
                else if (handler.ShouldProcess(file))
                {
                    handler.OnBeforeExtraction(file, relativePath, log);

                    // Read metadata
                    using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        try
                        {
                            var directories = ImageMetadataReader.ReadMetadata(stream).ToList();
                            handler.OnExtractionSuccess(file, directories, relativePath, log, stream.Position);
                        }
                        catch (Exception e)
                        {
                            handler.OnExtractionError(file, e, log, stream.Position);
                        }
                    }
                }
            }
        }
Beispiel #30
0
        private static DateTime?GetImageCreatedDate(string file)
        {
            var directories     = ImageMetadataReader.ReadMetadata(file);
            var subIfdDirectory = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault();

            return(subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTimeOriginal));
        }