public static DirectoryList ReadMetadata(Stream stream) { if (!stream.CanSeek) { throw new ArgumentException("Must support seek", nameof(stream)); } var data = new byte[512]; var bytesRead = stream.Read(data, 0, 512); if (bytesRead == 0) { throw new IOException("Stream is empty"); } stream.Seek(-bytesRead, SeekOrigin.Current); for (var i = 0; i < bytesRead - 2; i++) { // Look for the first three bytes of a JPEG encoded file if (data[i] == 0xff && data[i + 1] == 0xd8 && data[i + 2] == 0xff) { stream.Seek(i, SeekOrigin.Current); break; } } return(JpegMetadataReader.ReadMetadata(stream)); }
public void ResizeJPG(String fileName) { Metadata metadata = JpegMetadataReader.ReadMetadata(new FileInfo(fileName)); foreach (ExifDirectory _dir in metadata) { _dir.WriteThumbnail(fileName + "_thumb.jpg"); break; } /* Bitmap SourceBitmap = new Bitmap(fileName); * * if (SourceBitmap.PhysicalDimension.Width >= SourceBitmap.PhysicalDimension.Height) * { // landscape * Bitmap newimage = new Bitmap(296, 196); * using (Graphics g = Graphics.FromImage(newimage)) * g.DrawImage(SourceBitmap, 0, 0, 296, 196); * newimage.Save(fileName+"_landscape.jpg", ImageFormat.Jpeg); * } // portrait * else * { * Bitmap newimage = new Bitmap(196, 296); * using (Graphics g = Graphics.FromImage(newimage)) * g.DrawImage(SourceBitmap, 0, 0, 196, 296); * newimage.Save(fileName+"_portrait.jpg", ImageFormat.Jpeg); * }*/ }
DateTime getPhotoTime(string fn) { DateTime dtaken = DateTime.MinValue; if (filedatecache.ContainsKey(fn)) { return((DateTime)filedatecache[fn]); } try { Metadata lcMetadata = null; try { FileInfo lcImgFile = new FileInfo(fn); // Loading all meta data lcMetadata = JpegMetadataReader.ReadMetadata(lcImgFile); } catch (JpegProcessingException e) { log.InfoFormat(e.Message); return(dtaken); } foreach (AbstractDirectory lcDirectory in lcMetadata) { if (lcDirectory.ContainsTag(0x9003)) { dtaken = lcDirectory.GetDate(0x9003); log.InfoFormat("does " + lcDirectory.GetTagName(0x9003) + " " + dtaken); filedatecache[fn] = dtaken; break; } } ////// old method, works, just slow /* * Image myImage = Image.FromFile(fn); * PropertyItem propItem = myImage.GetPropertyItem(36867); // 36867 // 306 * * //Convert date taken metadata to a DateTime object * string sdate = Encoding.UTF8.GetString(propItem.Value).Trim(); * string secondhalf = sdate.Substring(sdate.IndexOf(" "), (sdate.Length - sdate.IndexOf(" "))); * string firsthalf = sdate.Substring(0, 10); * firsthalf = firsthalf.Replace(":", "-"); * sdate = firsthalf + secondhalf; * dtaken = DateTime.Parse(sdate); * * myImage.Dispose(); */ } catch { } return(dtaken); }
} // 짐벌 yaw : GimbalYawDegree public MetaData(string file_path) { try { var readers = new IJpegSegmentMetadataReader[] { new ExifReader(), new XmpReader() }; var directories = JpegMetadataReader.ReadMetadata(file_path, readers); // JPEG 파일 정보 ExifSubIfdDirectory sub_directory = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault(); SetExifData(sub_directory); // DJI XMP 정보 설정 // 드론, 짐벌 정보 XmpDirectory xmp_directory = directories.OfType <XmpDirectory>().FirstOrDefault(); SetXmpData(xmp_directory); } catch (JpegProcessingException e) { throw e; } catch (IOException e) { throw e; } }
/// <summary>Reads metadata from an <see cref="Stream"/>.</summary> /// <param name="stream">A stream from which the file data may be read. The stream must be positioned at the beginning of the file's data.</param> /// <returns>A list of <see cref="Directory"/> instances containing the various types of metadata found within the file's data.</returns> /// <exception cref="ImageProcessingException">The file type is unknown, or processing errors occurred.</exception> /// <exception cref="System.IO.IOException"/> public static DirectoryList ReadMetadata(Stream stream) { var fileType = FileTypeDetector.DetectFileType(stream); var directories = new List <Directory>(); directories.AddRange(fileType switch { FileType.Arw => TiffMetadataReader.ReadMetadata(stream), FileType.Avi => AviMetadataReader.ReadMetadata(stream), FileType.Bmp => BmpMetadataReader.ReadMetadata(stream), FileType.Crx => QuickTimeMetadataReader.ReadMetadata(stream), FileType.Cr2 => TiffMetadataReader.ReadMetadata(stream), FileType.Eps => EpsMetadataReader.ReadMetadata(stream), FileType.Gif => GifMetadataReader.ReadMetadata(stream), FileType.Ico => IcoMetadataReader.ReadMetadata(stream), FileType.Jpeg => JpegMetadataReader.ReadMetadata(stream), FileType.Mp3 => Mp3MetadataReader.ReadMetadata(stream), FileType.Nef => TiffMetadataReader.ReadMetadata(stream), FileType.Netpbm => new Directory[] { NetpbmMetadataReader.ReadMetadata(stream) }, FileType.Orf => TiffMetadataReader.ReadMetadata(stream), FileType.Pcx => new Directory[] { PcxMetadataReader.ReadMetadata(stream) }, FileType.Png => PngMetadataReader.ReadMetadata(stream), FileType.Psd => PsdMetadataReader.ReadMetadata(stream), FileType.QuickTime => QuickTimeMetadataReader.ReadMetadata(stream), FileType.Raf => RafMetadataReader.ReadMetadata(stream), FileType.Rw2 => TiffMetadataReader.ReadMetadata(stream), FileType.Tga => TgaMetadataReader.ReadMetadata(stream), FileType.Tiff => TiffMetadataReader.ReadMetadata(stream), FileType.Wav => WavMetadataReader.ReadMetadata(stream), FileType.WebP => WebPMetadataReader.ReadMetadata(stream), FileType.Unknown => throw new ImageProcessingException("File format could not be determined"), _ => Enumerable.Empty <Directory>() });
/// <summary> /// Shows only IPTC directory and only the TAG_HEADLINE value for one file. /// </summary> /// <param name="aFileName">the image file name (ex: c:/temp/a.jpg)</param> /// <returns>The information about IPTC for this image but only the TAG_HEADLINE tag as a string</returns> public static string ShowOneFileOnlyIptcOnlyTagTAG_HEADLINE(string aFileName) { Metadata lcMetadata = null; try { FileInfo lcImgFile = new FileInfo(aFileName); // Loading all meta data lcMetadata = JpegMetadataReader.ReadMetadata(lcImgFile); } catch (JpegProcessingException e) { Console.Error.WriteLine(e.Message); return("Error"); } // Now try to print them StringBuilder lcBuff = new StringBuilder(1024); lcBuff.Append("---> ").Append(aFileName).Append(" <---").AppendLine(); // We want anly IPCT directory IptcDirectory lcIptDirectory = (IptcDirectory)lcMetadata.GetDirectory("com.drew.metadata.iptc.IptcDirectory"); if (lcIptDirectory == null) { lcBuff.Append("No Iptc for this image.!").AppendLine(); return(lcBuff.ToString()); } // We look for potential error if (lcIptDirectory.HasError) { Console.Error.WriteLine("Some errors were found, activate trace using /d:TRACE option with the compiler"); } // Then we want only the TAG_HEADLINE tag if (!lcIptDirectory.ContainsTag(IptcDirectory.TAG_HEADLINE)) { lcBuff.Append("No TAG_HEADLINE for this image.!").AppendLine(); return(lcBuff.ToString()); } string lcTagDescription = null; try { lcTagDescription = lcIptDirectory.GetDescription(IptcDirectory.TAG_HEADLINE); } catch (MetadataException e) { Console.Error.WriteLine(e.Message); } string lcTagName = lcIptDirectory.GetTagName(IptcDirectory.TAG_HEADLINE); lcBuff.Append(lcTagName).Append('=').Append(lcTagDescription).AppendLine(); return(lcBuff.ToString()); }
public DateTime JpegMetadataReaderBenchmark() { _stream.Position = 0; var directories = JpegMetadataReader.ReadMetadata(_stream); var subIfdDirectory = directories.OfType <ExifSubIfdDirectory>().First(); return(subIfdDirectory.GetDateTime(ExifDirectoryBase.TagDateTimeOriginal)); }
public virtual Task <Size> GetImageSize(byte[]?bytes) { return(Task.Run(() => { if (bytes == null) { return Size.Empty; } try { using (var stream = new MemoryStream(bytes)) { var type = FileTypeDetector.DetectFileType(stream); stream.Seek(0, SeekOrigin.Begin); switch (type) { case FileType.Jpeg: var jpeg = JpegMetadataReader.ReadMetadata(stream); var jpegdir = jpeg.OfType <JpegDirectory>().FirstOrDefault(); return new Size(jpegdir.GetImageWidth(), jpegdir.GetImageHeight()); case FileType.Png: var png = PngMetadataReader.ReadMetadata(stream); var pngdir = png.OfType <PngDirectory>().FirstOrDefault(); return new Size(pngdir.GetInt32(PngDirectory.TagImageWidth), pngdir.GetInt32(PngDirectory.TagImageHeight)); case FileType.Gif: var gif = GifMetadataReader.ReadMetadata(stream); var gifdir = gif.OfType <GifHeaderDirectory>().FirstOrDefault(); return new Size(gifdir.GetInt32(GifHeaderDirectory.TagImageWidth), gifdir.GetInt32(GifHeaderDirectory.TagImageHeight)); case FileType.WebP: var webp = WebPMetadataReader.ReadMetadata(stream); var webpdir = webp.OfType <WebPDirectory>().FirstOrDefault(); return new Size(webpdir.GetInt32(WebPDirectory.TagImageWidth), webpdir.GetInt32(WebPDirectory.TagImageHeight)); case FileType.Bmp: var bmp = BmpMetadataReader.ReadMetadata(stream); var bmpdir = bmp.OfType <BmpHeaderDirectory>().FirstOrDefault(); return new Size(bmpdir.GetInt32(BmpHeaderDirectory.TagImageWidth), bmpdir.GetInt32(BmpHeaderDirectory.TagImageHeight)); default: return Size.Empty; } } } catch (Exception) { //Crashes.TrackError(e); // No need to track this } return Size.Empty; })); }
/// <summary> /// Shows all metadata and all tag for one file. /// </summary> /// <param name="aFileName">the image file name (ex: c:/temp/a.jpg)</param> /// <returns>The information about the image as a string</returns> public static String ShowOneFileAllMetaDataAllTag(string aFileName) { Metadata lcMetadata = null; try { FileInfo lcImgFile = new FileInfo(aFileName); // Loading all meta data lcMetadata = JpegMetadataReader.ReadMetadata(lcImgFile); } catch (JpegProcessingException e) { Console.Error.WriteLine(e.Message); return("Error"); } // Now try to print them StringBuilder lcBuff = new StringBuilder(1024); lcBuff.Append("---> ").Append(aFileName).Append(" <---").AppendLine(); // We want all directory, so we iterate on each foreach (AbstractDirectory lcDirectory in lcMetadata) { // We look for potential error if (lcDirectory.HasError) { Console.Error.WriteLine("Some errors were found, activate trace using /d:TRACE option with the compiler"); } lcBuff.Append("---+ ").Append(lcDirectory.GetName()).AppendLine(); // Then we want all tags, so we iterate on the current directory foreach (Tag lcTag in lcDirectory) { string lcTagDescription = null; try { lcTagDescription = lcTag.GetDescription(); } catch (MetadataException e) { Console.Error.WriteLine(e.Message); } string lcTagName = lcTag.GetTagName(); lcBuff.Append(lcTagName).Append('=').Append(lcTagDescription).AppendLine(); lcTagDescription = null; lcTagName = null; } } lcMetadata = null; return(lcBuff.ToString()); }
public static IEnumerable <MetadataExtractor.Directory> GetFileMetaData(string fullpath) { var type = GetType(fullpath); IEnumerable <MetadataExtractor.Directory> data = type switch { FileTypeEnum.JPG => JpegMetadataReader.ReadMetadata(fullpath), FileTypeEnum.CR2 => TiffMetadataReader.ReadMetadata(fullpath), FileTypeEnum.PNG => PngMetadataReader.ReadMetadata(fullpath), _ => throw new Exception(),// is unreachable }; return(data.ToList()); }
ReadMetadata([NotNull] Stream stream) { var fileType = FileTypeDetector.DetectFileType(stream); switch (fileType) { case FileType.Jpeg: return(JpegMetadataReader.ReadMetadata(stream)); case FileType.Tiff: case FileType.Arw: case FileType.Cr2: case FileType.Nef: case FileType.Orf: case FileType.Rw2: return(TiffMetadataReader.ReadMetadata(stream)); case FileType.Psd: return(PsdMetadataReader.ReadMetadata(stream)); case FileType.Png: return(PngMetadataReader.ReadMetadata(stream)); case FileType.Bmp: return(new Directory[] { BmpMetadataReader.ReadMetadata(stream) }); case FileType.Gif: return(GifMetadataReader.ReadMetadata(stream)); case FileType.Ico: return(IcoMetadataReader.ReadMetadata(stream)); case FileType.Pcx: return(new Directory[] { PcxMetadataReader.ReadMetadata(stream) }); case FileType.Riff: return(WebPMetadataReader.ReadMetadata(stream)); case FileType.Raf: return(RafMetadataReader.ReadMetadata(stream)); case FileType.QuickTime: return(QuickTimeMetadataReader.ReadMetadata(stream)); case FileType.Netpbm: return(new Directory[] { NetpbmMetadataReader.ReadMetadata(stream) }); } throw new ImageProcessingException("File format is not supported"); }
/// <summary> /// メタデータの構造データを取得する /// </summary> /// <param name="filePath">ファイルパス</param> /// <param name="fileExtensionType">ファイルの拡張子</param> /// <returns>メタデータの構造データ</returns> private static IEnumerable <Directory> GetMetadataDirectories(string filePath, FileExtensionType fileExtensionType) { var directories = fileExtensionType switch { FileExtensionType.Jpeg => JpegMetadataReader.ReadMetadata(filePath), FileExtensionType.Bmp => BmpMetadataReader.ReadMetadata(filePath), FileExtensionType.Png => PngMetadataReader.ReadMetadata(filePath), FileExtensionType.Gif => GifMetadataReader.ReadMetadata(filePath), FileExtensionType.Tiff or FileExtensionType.Dng or FileExtensionType.Nef => TiffMetadataReader.ReadMetadata(filePath), FileExtensionType.Unknown or _ => throw new ArgumentOutOfRangeException(nameof(fileExtensionType)), }; return(directories); }
private static string ExtractFileMetadata(string tempFileDirectory) { using FileStream fileStream = File.OpenRead(tempFileDirectory); StringBuilder stringBuilder = new StringBuilder(); var metadataDirectories = JpegMetadataReader.ReadMetadata(fileStream); foreach (var directory in metadataDirectories) { foreach (var tag in directory.Tags) { stringBuilder.AppendLine($"{tag.Name} = {tag.Description}"); } } return(stringBuilder.ToString()); }
public static Com.Drew.Metadata.Metadata ReadMetadata([NotNull] InputStream inputStream) { BufferedInputStream bufferedInputStream = inputStream is BufferedInputStream ? (BufferedInputStream)inputStream : new BufferedInputStream(inputStream); FileType fileType = FileTypeDetector.DetectFileType(bufferedInputStream) ?? FileType.Unknown; if (fileType == FileType.Jpeg) { return(JpegMetadataReader.ReadMetadata(bufferedInputStream)); } if (fileType == FileType.Tiff || fileType == FileType.Arw || fileType == FileType.Cr2 || fileType == FileType.Nef || fileType == FileType.Orf || fileType == FileType.Rw2) { return(TiffMetadataReader.ReadMetadata(bufferedInputStream)); } if (fileType == FileType.Psd) { return(PsdMetadataReader.ReadMetadata(bufferedInputStream)); } if (fileType == FileType.Png) { return(PngMetadataReader.ReadMetadata(bufferedInputStream)); } if (fileType == FileType.Bmp) { return(BmpMetadataReader.ReadMetadata(bufferedInputStream)); } if (fileType == FileType.Gif) { return(GifMetadataReader.ReadMetadata(bufferedInputStream)); } if (fileType == FileType.Ico) { return(IcoMetadataReader.ReadMetadata(bufferedInputStream)); } if (fileType == FileType.Pcx) { return(PcxMetadataReader.ReadMetadata(bufferedInputStream)); } if (fileType == FileType.Riff) { return(WebpMetadataReader.ReadMetadata(bufferedInputStream)); } throw new ImageProcessingException("File format is not supported"); }
private static Tuple <string, string, string[]> AlternativeReadingMetadataMethod(IFileSystem fileSystem, string filePath) { using var fs = fileSystem.File.OpenRead(filePath); var metadata = (JpegMetadataReader.ReadMetadata(fs)); var iFD0Directory = metadata.OfType <ExifIfd0Directory>().FirstOrDefault(); var exifIfd0Descriptor = new ExifIfd0Descriptor(iFD0Directory); var Ifd0Description = exifIfd0Descriptor.GetDescription(ExifIfd0Directory.TagImageDescription); var Ifd0Keywords = exifIfd0Descriptor.GetDescription(ExifIfd0Directory.TagWinKeywords); var Ifd0Title = exifIfd0Descriptor.GetDescription(ExifIfd0Directory.TagWinTitle); //var subIfdDirectory = metadata.OfType<ExifSubIfdDirectory>().FirstOrDefault(); //var subIfdDescriptor = new ExifSubIfdDescriptor(subIfdDirectory); // returns something like 4261 pixels //var dagExifImageWidth = subIfdDescriptor.GetDescription(ExifDirectoryBase.TagExifImageWidth); //var dagExifImageHeight = subIfdDescriptor.GetDescription(ExifDirectoryBase.TagExifImageHeight); var thumbnailDirectory = metadata.OfType <ExifThumbnailDirectory>().FirstOrDefault(); var thumbnailDescriptor = new ExifThumbnailDescriptor(thumbnailDirectory); var thumbnailOffset = thumbnailDescriptor.GetDescription(ExifThumbnailDirectory.TagThumbnailOffset); var thumbnailYResolution = thumbnailDescriptor.GetDescription(ExifThumbnailDirectory.TagYResolution); var thumbnailXResolution = thumbnailDescriptor.GetDescription(ExifThumbnailDirectory.TagXResolution); var thumbnailLength = thumbnailDescriptor.GetDescription(ExifThumbnailDirectory.TagThumbnailLength); var thumbnailCompression = thumbnailDescriptor.GetDescription(ExifThumbnailDirectory.TagCompression); var IPTCDirectory = metadata.OfType <IptcDirectory>().FirstOrDefault(); var iptcDescriptor = new IptcDescriptor(IPTCDirectory); var IPTCDescription = iptcDescriptor.GetDescription(IptcDirectory.TagCaption); var IPTCKeywords = iptcDescriptor.GetDescription(IptcDirectory.TagKeywords); // like "TestFile1Kw1;TestFile1Kw2;TestFile1Kw3;TestFile1Kw4" var IPTCTitle = iptcDescriptor.GetDescription(IptcDirectory.TagObjectName); var keywordsAsString = string.IsNullOrWhiteSpace(Ifd0Keywords) ? IPTCKeywords : Ifd0Keywords; var arrayOrKeywords = keywordsAsString?.Split(';'); var title = string.IsNullOrWhiteSpace(Ifd0Title) ? IPTCTitle : Ifd0Title; var description = string.IsNullOrWhiteSpace(Ifd0Description) ? IPTCDescription : Ifd0Description; return(new Tuple <string, string, string[]>(title, description, arrayOrKeywords)); }
public static Com.Drew.Metadata.Metadata ReadMetadata(InputStream inputStream) { InputStream bufferedInputStream = inputStream is BufferedInputStream ? inputStream : new BufferedInputStream(inputStream); int magicNumber = PeekMagicNumber(bufferedInputStream); if (magicNumber == -1) { throw new ImageProcessingException("Could not determine file's magic number."); } // This covers all JPEG files if ((magicNumber & JpegFileMagicNumber) == JpegFileMagicNumber) { return(JpegMetadataReader.ReadMetadata(bufferedInputStream)); } // This covers all TIFF and camera RAW files if (magicNumber == IntelTiffMagicNumber || magicNumber == MotorolaTiffMagicNumber) { return(TiffMetadataReader.ReadMetadata(bufferedInputStream)); } // This covers PSD files // TODO we should really check all 4 bytes of the PSD magic number if (magicNumber == PsdMagicNumber) { return(PsdMetadataReader.ReadMetadata(bufferedInputStream)); } // This covers BMP files if (magicNumber == PngMagicNumber) { return(PngMetadataReader.ReadMetadata(bufferedInputStream)); } // This covers BMP files if (magicNumber == BmpMagicNumber) { return(BmpMetadataReader.ReadMetadata(bufferedInputStream)); } // This covers GIF files if (magicNumber == GifMagicNumber) { return(GifMetadataReader.ReadMetadata(bufferedInputStream)); } throw new ImageProcessingException("File format is not supported"); }
private String GenerateThumbnail(FileInfo OriginalJpegFile) { Metadata metadata = JpegMetadataReader.ReadMetadata(OriginalJpegFile); try { foreach (ExifDirectory _dir in metadata) { // generate thumbnail and cache it... // first we need the ID... String ID = OriginalJpegFile.Name + OriginalJpegFile.LastWriteTime.Ticks; byte[] data = _dir.GetThumbnailData(); AddToCache(ID, data); return(ID); } } catch (Exception) { } return(null); }
public override void analyzeFile() { com.drew.metadata.Metadata m; try { if (strExt.ToLower() == ".raw" || strExt.ToLower() == ".cr2" || strExt.ToLower() == ".crw") { m = TiffMetadataReader.ReadMetadata(stm); } else { m = JpegMetadataReader.ReadMetadata(stm); } IEnumerator <AbstractDirectory> lcDirectoryEnum = m.GetDirectoryIterator(); while (lcDirectoryEnum.MoveNext()) { if (lcDirectoryEnum.Current.GetName() != "Jpeg Makernote") { SerializableDictionary <string, string> dicTags = new SerializableDictionary <string, string>(); AbstractDirectory lcDirectory = lcDirectoryEnum.Current; IEnumerator <Tag> lcTagsEnum = lcDirectory.GetTagIterator(); while (lcTagsEnum.MoveNext()) { Tag tag = lcTagsEnum.Current; if (tag.GetTagName() == "Thumbnail Data") { Thumbnail = (byte[])tag.GetTagValue(); } string lcDescription = ""; try { lcDescription = tag.GetDescription(); } catch { }; string lcName = tag.GetTagName(); if (lcName.ToLower().StartsWith("unknown") || lcDescription.ToLower().StartsWith("unknown")) { continue; } lcName = Functions.RemoveAccentsWithNormalization(lcName); lcDescription = Functions.RemoveAccentsWithNormalization(lcDescription); if (lcName.ToLower() == "owner name" || lcName.ToLower() == "copyright") { if (!string.IsNullOrEmpty(lcDescription) && lcDescription.Trim() != string.Empty && !lcDescription.ToLower().Contains("digital") && !lcDescription.ToLower().Contains("camera") && !lcDescription.ToLower().Contains("(c)") && !lcDescription.ToLower().Contains("copyright")) { FoundUsers.AddUniqueItem(lcDescription, false, "Copyright/Owner name"); } } if (lcName.ToLower() == "software") { string strSoftware = Analysis.ApplicationAnalysis.GetApplicationsFromString(lcDescription.Trim()); if (!FoundMetaData.Applications.Items.Any(A => A.Name == strSoftware)) { FoundMetaData.Applications.Items.Add(new ApplicationsItem(strSoftware)); } } if (lcName.ToLower() == "model") { FoundMetaData.Model = lcDescription.Trim(); } dicTags.Add(lcName, lcDescription); } dicAnotherMetadata.Add(lcDirectory.GetName(), dicTags); } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Error analizing EXIF metadata ({e.ToString()})"); } finally { this.stm.Close(); } }
protected override async Task <Metadata> ReadMetadata( Metadata metadata, MetadataReaderFileInfo fileInfo, MetadataReaderOption option) { var directories = await _fileService.ReadFileStream(fileInfo.FileHandle, readStream => { if (fileInfo.MimeType == MimeType.image_png) { return(ValueTask.FromResult(PngMetadataReader.ReadMetadata(readStream))); } if (fileInfo.MimeType == MimeType.image_jpeg) { return(ValueTask.FromResult(JpegMetadataReader.ReadMetadata(readStream))); } if (fileInfo.MimeType == MimeType.image_bmp) { return(ValueTask.FromResult(BmpMetadataReader.ReadMetadata(readStream))); } if (fileInfo.MimeType == MimeType.image_gif) { return(ValueTask.FromResult(GifMetadataReader.ReadMetadata(readStream))); } if (fileInfo.MimeType == MimeType.image_webp) { return(ValueTask.FromResult(WebPMetadataReader.ReadMetadata(readStream))); } return(ValueTask.FromResult(MetadataExtractor.ImageMetadataReader.ReadMetadata(readStream))); }); foreach (var directory in directories) { if (directory is JpegDirectory jpegDirectory) { ParseJpegDirectory(jpegDirectory, metadata); } else if (directory is WebPDirectory webPDirectory) { ParseWebPDirectory(webPDirectory, metadata); } else if (directory is ExifIfd0Directory exifIfd0Directory) { ParseExifDirectory(exifIfd0Directory, metadata); } else if (directory is ExifSubIfdDirectory exifSubIfdDirectory) { ParseExifDirectory(exifSubIfdDirectory, metadata); } else if (directory is PngDirectory pngDirectory) { ParsePngDirectory(pngDirectory, metadata); } else if (directory is XmpDirectory xmpDirectory) { ParseXmpDirectory(xmpDirectory, metadata); } else if (directory is CanonMakernoteDirectory canonMakernoteDirectory) { ParseCanonMakernoteDirectory(canonMakernoteDirectory, metadata); } } return(metadata); }
public void TestExtractMetadataUsingStream() { Validate(JpegMetadataReader.ReadMetadata(new FileStream("Tests/Data/withExif.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))); }
public void TestExtractMetadata() { Validate(JpegMetadataReader.ReadMetadata("Tests/Data/withExif.jpg")); }
private static void Main() { const string filePath = "../MetadataExtractor.Tests/Data/withIptcExifGps.jpg"; 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); } // // SCENARIO 2: SPECIFIC FILE TYPE // // If you know the file to be a JPEG, you may invoke the JpegMetadataReader, rather than the generic reader // used in approach 1. Similarly, if you knew the file to be a TIFF/RAW image you might use TiffMetadataReader, // PngMetadataReader for PNG files, BmpMetadataReader for BMP files, or GifMetadataReader for GIF files. // // Using the specific reader offers a very, very slight performance improvement. // try { var directories = JpegMetadataReader.ReadMetadata(filePath); Print(directories, "Using JpegMetadataReader"); } catch (JpegProcessingException e) { PrintError(e); } catch (IOException e) { PrintError(e); } // // APPROACH 3: SPECIFIC METADATA TYPE // // If you only wish to read a subset of the supported metadata types, you can do this by // passing the set of readers to use. // // This currently only applies to JPEG file processing. // try { // Handle only Exif and IPTC from JPEG var readers = new IJpegSegmentMetadataReader[] { new ExifReader(), new IptcReader() }; var directories = JpegMetadataReader.ReadMetadata(filePath, readers); Print(directories, "Using JpegMetadataReader for Exif and IPTC only"); } catch (JpegProcessingException e) { PrintError(e); } catch (IOException e) { PrintError(e); } // Write all extracted values to stdout void Print(IEnumerable <Directory> directories, string method) { Console.WriteLine(); Console.WriteLine("-------------------------------------------------"); Console.Write(' '); Console.WriteLine(method); Console.WriteLine("-------------------------------------------------"); Console.WriteLine(); // Extraction gives us potentially many directories foreach (var directory in directories) { // Each directory stores values in tags foreach (var tag in directory.Tags) { Console.WriteLine(tag); } // Each directory may also contain error messages foreach (var error in directory.Errors) { Console.Error.WriteLine("ERROR: " + error); } } } DateTime?GetTakenDateTime(IEnumerable <Directory> directories) { // obtain the Exif SubIFD directory var directory = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault(); if (directory == null) { return(null); } // query the tag's value if (directory.TryGetDateTime(ExifDirectoryBase.TagDateTimeOriginal, out var dateTime)) { return(dateTime); } return(null); } string GetExposureProgramDescription(IEnumerable <Directory> directories) { // obtain a specific directory var directory = directories.OfType <ExifSubIfdDirectory>().FirstOrDefault(); if (directory == null) { return(null); } // create a descriptor var descriptor = new ExifSubIfdDescriptor(directory); // get tag description return(descriptor.GetExposureProgramDescription()); } void PrintError(Exception exception) => Console.Error.WriteLine($"EXCEPTION: {exception}"); }
private static void Main() { const string filePath = "../MetadataExtractor.Tests/Data/withIptcExifGps.jpg"; 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); } // // SCENARIO 2: SPECIFIC FILE TYPE // // If you know the file to be a JPEG, you may invoke the JpegMetadataReader, rather than the generic reader // used in approach 1. Similarly, if you knew the file to be a TIFF/RAW image you might use TiffMetadataReader, // PngMetadataReader for PNG files, BmpMetadataReader for BMP files, or GifMetadataReader for GIF files. // // Using the specific reader offers a very, very slight performance improvement. // try { var directories = JpegMetadataReader.ReadMetadata(filePath); Print(directories, "Using JpegMetadataReader"); } catch (JpegProcessingException e) { PrintError(e); } catch (IOException e) { PrintError(e); } // // APPROACH 3: SPECIFIC METADATA TYPE // // If you only wish to read a subset of the supported metadata types, you can do this by // passing the set of readers to use. // // This currently only applies to JPEG file processing. // try { // Handle only Exif and IPTC from JPEG var readers = new IJpegSegmentMetadataReader[] { new ExifReader(), new IptcReader() }; var directories = JpegMetadataReader.ReadMetadata(filePath, readers); Print(directories, "Using JpegMetadataReader for Exif and IPTC only"); } catch (JpegProcessingException e) { PrintError(e); } catch (IOException e) { PrintError(e); }
public void ExtractMetadataUsingStream() { using (var stream = new FileStream("Data/withExif.jpg", FileMode.Open, FileAccess.Read, FileShare.Read)) Validate(JpegMetadataReader.ReadMetadata(stream)); }
private void BUT_samplephoto_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "*.jpg|*.jpg"; ofd.ShowDialog(); if (File.Exists(ofd.FileName)) { string fn = ofd.FileName; Metadata lcMetadata = null; try { FileInfo lcImgFile = new FileInfo(fn); // Loading all meta data lcMetadata = JpegMetadataReader.ReadMetadata(lcImgFile); } catch (JpegProcessingException ex) { log.InfoFormat(ex.Message); return; } foreach (AbstractDirectory lcDirectory in lcMetadata) { foreach (var tag in lcDirectory) { Console.WriteLine(lcDirectory.GetName() + " - " + tag.GetTagName() + " " + tag.GetTagValue().ToString()); } if (lcDirectory.ContainsTag(ExifDirectory.TAG_EXIF_IMAGE_HEIGHT)) { TXT_imgheight.Text = lcDirectory.GetInt(ExifDirectory.TAG_EXIF_IMAGE_HEIGHT).ToString(); } if (lcDirectory.ContainsTag(ExifDirectory.TAG_EXIF_IMAGE_WIDTH)) { TXT_imgwidth.Text = lcDirectory.GetInt(ExifDirectory.TAG_EXIF_IMAGE_WIDTH).ToString(); } if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_PLANE_X_RES)) { var unit = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_PLANE_UNIT); // TXT_senswidth.Text = lcDirectory.GetDouble(ExifDirectory.TAG_FOCAL_PLANE_X_RES).ToString(); } if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_PLANE_Y_RES)) { var unit = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_PLANE_UNIT); // TXT_sensheight.Text = lcDirectory.GetDouble(ExifDirectory.TAG_FOCAL_PLANE_Y_RES).ToString(); } if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_LENGTH)) { try { var item = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_LENGTH); num_focallength.Value = (decimal)item; } catch { } } if (lcDirectory.ContainsTag(ExifDirectory.TAG_DATETIME_ORIGINAL)) { } } } }
public bool TryLoad(FileInfo file, out BackgroundImage bgImg) { bgImg = null; if (file == null || !file.Exists) { return(false); } if (!string.Equals(file.Extension, ".jpg", StringComparison.OrdinalIgnoreCase) && !string.Equals(file.Extension, ".jpeg", StringComparison.OrdinalIgnoreCase)) { return(false); } IReadOnlyList <MetadataExtractor.Directory> directories = JpegMetadataReader.ReadMetadata(file.FullName); int width = 0; int height = 0; DateTimeOffset timestamp = default; string make = string.Empty; string model = string.Empty; foreach (var dir in directories) { if (timestamp == default(DateTimeOffset)) { if (dir.TryGetDateTime(ExifDirectoryBase.TagDateTimeOriginal, out var dateTime)) { timestamp = new DateTimeOffset(dateTime); } } if (width <= 0) { if (dir.ContainsTag(ExifDirectoryBase.TagExifImageWidth)) { dir.TryGetInt32(ExifDirectoryBase.TagExifImageWidth, out width); } else if (dir.ContainsTag(ExifDirectoryBase.TagImageWidth)) { dir.TryGetInt32(ExifDirectoryBase.TagImageWidth, out width); } } if (height <= 0) { if (dir.ContainsTag(ExifDirectoryBase.TagExifImageHeight)) { dir.TryGetInt32(ExifDirectoryBase.TagExifImageHeight, out height); } else if (dir.ContainsTag(ExifDirectoryBase.TagImageHeight)) { dir.TryGetInt32(ExifDirectoryBase.TagImageHeight, out height); } } if (make.Length == 0 && dir.ContainsTag(ExifDirectoryBase.TagMake)) { make = dir.GetString(ExifDirectoryBase.TagMake); } if (string.IsNullOrEmpty(model) && dir.ContainsTag(ExifDirectoryBase.TagModel)) { model = dir.GetString(ExifDirectoryBase.TagModel); } } string camName = $"{make ?? string.Empty} {model ?? string.Empty}"; if (timestamp.Year < 1990) { this._logger.LogWarning($"\n{file.Name}: timestamp missing: {timestamp}"); } if (height <= 0 || width <= 0) { this._logger.LogWarning($"\n{file.Name}: width/height missing: {width}x{height}"); } if (string.IsNullOrWhiteSpace(camName)) { this._logger.LogWarning($"{file.Name}: no model/make"); } // gps location may be null var gpsLocation = directories .OfType <GpsDirectory>() .Select(s => s.GetGeoLocation()) .Where(w => w != null) .Select(s => new Models.OpenStreetMap.GeoLocation(s.Latitude, s.Longitude)) .FirstOrDefault(); bgImg = new BackgroundImage(file.FullName, width, height, timestamp, camName, gpsLocation); return(true); }
/// <summary>Reads metadata from an <see cref="Stream"/>.</summary> /// <param name="stream">A stream from which the file data may be read. The stream must be positioned at the beginning of the file's data.</param> /// <returns>A list of <see cref="Directory"/> instances containing the various types of metadata found within the file's data.</returns> /// <exception cref="ImageProcessingException">The file type is unknown, or processing errors occurred.</exception> /// <exception cref="System.IO.IOException"/> public static DirectoryList ReadMetadata(Stream stream) { var fileType = FileTypeDetector.DetectFileType(stream); var fileTypeDirectory = new FileTypeDirectory(fileType); switch (fileType) { case FileType.Jpeg: return(Append(JpegMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Tiff: case FileType.Arw: case FileType.Cr2: case FileType.Nef: case FileType.Orf: case FileType.Rw2: return(Append(TiffMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Psd: return(Append(PsdMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Png: return(Append(PngMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Bmp: return(Append(BmpMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Gif: return(Append(GifMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Ico: return(Append(IcoMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Pcx: return(new Directory[] { PcxMetadataReader.ReadMetadata(stream), fileTypeDirectory }); case FileType.WebP: return(Append(WebPMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Avi: return(Append(AviMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Wav: return(Append(WavMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Raf: return(Append(RafMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.QuickTime: case FileType.Crx: return(Append(QuickTimeMetadataReader.ReadMetadata(stream), fileTypeDirectory)); case FileType.Netpbm: return(new Directory[] { NetpbmMetadataReader.ReadMetadata(stream), fileTypeDirectory }); case FileType.Unknown: throw new ImageProcessingException("File format could not be determined"); case FileType.Riff: case FileType.Crw: default: throw new ImageProcessingException("File format is not supported"); }
public static void Main(string[] someArgs) { if (someArgs.Length == 0) { Console.Error.WriteLine("Use: MetaDataExtractor [FilePaths|DirectoryPaths] [noUnknown|asXml|asXml2|doSub]"); Console.Error.WriteLine(" - noUnknown: will hide unknown metadata tag"); Console.Error.WriteLine(" - asXml : will generate an XML stream"); Console.Error.WriteLine(" - asXml2 : will generate an XML stream with more information than asXml"); Console.Error.WriteLine(" - doSub : will search subdirectories for *.jpg, *.raw, *.cr2, *.crw"); Console.Error.WriteLine("Examples:"); Console.Error.WriteLine(" - Will show you MyImage.jpg info as text:"); Console.Error.WriteLine(" MetaDataExtractor c:\\MyImage.jpg"); Console.Error.WriteLine(" or "); Console.Error.WriteLine(" - Will show you all *.jpg|*.raw|*.cr2|*.crw in c:\\ and img1.jpg and img2.jpg info as text:"); Console.Error.WriteLine(" MetaDataExtractor c:\\ d:\\img1.jpg e:\\img2.jpg"); Console.Error.WriteLine(" - Will show you all *.jpg|*.raw|*.cr2|*.crw in c:\\ as text but with no unkown tags:"); Console.Error.WriteLine(" MetaDataExtractor c:\\ noUnknown"); Console.Error.WriteLine(" - Will show you all *.jpg|*.raw|*.cr2|*.crw in c:\\ as XML:"); Console.Error.WriteLine(" MetaDataExtractor c:\\ asXml"); Console.Error.WriteLine(" - Will show you all *.jpg|*.raw|*.cr2|*.crw in c:\\ as XML2 but with no unkown tags:"); Console.Error.WriteLine(" MetaDataExtractor c:\\ noUnknown asXml2"); Console.Error.WriteLine(" - Will show you all *.jpg|*.raw|*.cr2|*.crw in c:\\Temp\\ and all its subdirectories as XML but with no unkown tags:"); Console.Error.WriteLine(" MetaDataExtractor c:\\Temp noUnknown asXml doSub"); Console.Error.WriteLine(" - Will put in a file called sample.xml all c:\\Temp\\ *.jpg|*.raw|*.cr2|*.crw and all its subdirectories as XML but with no unkown tags:"); Console.Error.WriteLine(" MetaDataExtractor c:\\Temp noUnknown asXml doSub > sample.xml"); Console.Error.WriteLine("Cautions:"); Console.Error.WriteLine(" + Pointing on c:\\ with doSub option is a very bad idea ;-)"); } else { Run.FindAsXml(someArgs); Run.FindNoUnknown(someArgs); Run.FindDoSub(someArgs); StringBuilder lcGlobalBuff = new StringBuilder(1024); IOutPutTextStreamHandler lcXmlHandler = null; string dtdFile = null; if (Run.asXml == (byte)1) { lcXmlHandler = new XmlOutPutStreamHandler(); dtdFile = "MetadataExtractor.dtd"; } else if (Run.asXml == (byte)2) { lcXmlHandler = new XmlNewOutPutStreamHandler(); dtdFile = "MetadataExtractorNew.dtd"; } else { lcXmlHandler = new TxtOutPutStreamHandler(); } lcXmlHandler.DoUnknown = !Run.noUnknown; List <string> lcFileNameLst = Run.FindFileNames(someArgs); // Args for OutPutTextStream objects // Indicate your Xsl here string lcXslFileName = null; // For example: ="exif.xslt"; // Indicate if you want to use CDDATA in your XML stream string useCDDATA = "false"; string[] lcOutputParams = new string[] { "ISO-8859-1", lcXslFileName, lcFileNameLst.Count.ToString(), dtdFile, useCDDATA }; lcXmlHandler.StartTextStream(lcGlobalBuff, lcOutputParams); foreach (string lcFileName in lcFileNameLst) { StringBuilder lcBuff = new StringBuilder(2048); Metadata lcMetadata = null; try { FileInfo lcImgFileInfo = new FileInfo(lcFileName); if (lcFileName.ToLower().EndsWith(".raw") || lcFileName.ToLower().EndsWith(".cr2") || lcFileName.ToLower().EndsWith(".crw")) { lcMetadata = TiffMetadataReader.ReadMetadata(lcImgFileInfo); } else { lcMetadata = JpegMetadataReader.ReadMetadata(lcImgFileInfo); } lcXmlHandler.Metadata = lcMetadata; } catch (JpegProcessingException e) { Console.Error.WriteLine("Could note analyse the file '" + lcFileName + "' error message is:" + e.Message); break; } if (Run.asXml != (byte)0) { // First open file name tag lcBuff.Append("<file name=\""); lcXmlHandler.Normalize(lcBuff, lcFileName, false); lcBuff.Append("\">").AppendLine(); // Then create all directory tag lcBuff.Append(lcXmlHandler.AsText()); // Then close file tag lcBuff.Append("</file>").AppendLine().AppendLine(); } else { lcBuff.Append("-> "); lcXmlHandler.Normalize(lcBuff, lcFileName, false); lcBuff.Append(" <-").AppendLine(); // Then create all directory tag lcBuff.Append(lcXmlHandler.AsText()).AppendLine(); } lcMetadata = null; // Adds result for this file to big buffer lcGlobalBuff.Append(lcBuff); lcGlobalBuff.AppendLine(); } lcXmlHandler.EndTextStream(lcGlobalBuff, lcOutputParams); Console.Out.WriteLine(lcGlobalBuff.ToString()); } // Uncomment if you are running under VisualStudio // Console.In.ReadLine(); }
public void ExtractMetadataUsingStream() { using var stream = TestDataUtil.OpenRead("Data/withExif.jpg"); Validate(JpegMetadataReader.ReadMetadata(stream)); }
public void ExtractMetadataUsingPath() { Validate(JpegMetadataReader.ReadMetadata("Data/withExif.jpg")); }