public static void Run() { // ExStart:ReadAndModifyJpegEXIFTags // The path to the documents directory. string dataDir = RunExamples.GetDataDir_JPEG(); // Load an image using the factory method Load exposed by Image class using (Image image = Image.Load(dataDir + "aspose-logo.jpg")) { // Initialize an object of ExifData and fill it will image's EXIF information ExifData exif = ((JpegImage)image).ExifData; // Check if image has any EXIF entries defined if (exif != null) { // In order to get all EXIF tags, first get the Type of EXIF object Type type = exif.GetType(); //Get all properties of EXIF object into an array PropertyInfo[] properties = type.GetProperties(); // Iterate over the EXIF properties foreach (PropertyInfo property in properties) { // Display property name and its value Console.WriteLine(property.Name + ":" + property.GetValue(exif, null)); } } } // ExEnd:ReadAndModifyJpegEXIFTags }
public void GetMetaData() { var imageStream = new MemoryStream(File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + @"\TestData\full.jpg")); var result = Processing.ReadExifData(imageStream); var expected = new ExifData { ApertureValue = 4, CaptureDate = new DateTime(2014, 9, 18, 19, 24, 07), ExposureBiasValue = 0.33333333333333331, ExposureProgram = 3, ExposureTime = 0.2, FNumber = 4, FocalLength = 45.0, Make = "Canon", Model = "Canon EOS 6D", Title = "Der Kristof als Title" }; Assert.AreEqual(expected.ApertureValue, result.ApertureValue); Assert.AreEqual(expected.CaptureDate, result.CaptureDate); Assert.AreEqual(expected.ExposureBiasValue, result.ExposureBiasValue); Assert.AreEqual(expected.ExposureProgram, result.ExposureProgram); Assert.AreEqual(expected.ExposureTime, result.ExposureTime); Assert.AreEqual(expected.FNumber, result.FNumber); Assert.AreEqual(expected.FocalLength, result.FocalLength); Assert.AreEqual(expected.Make, result.Make); Assert.AreEqual(expected.Model, result.Model); Assert.AreEqual(expected.Title, result.Title); }
private static void SetLocationData(ExifProfile profile, ExifData exif) { var lat = GetExifDataFromTag <double[]>(profile, ExifTag.GPSLatitude); var lng = GetExifDataFromTag <double[]>(profile, ExifTag.GPSLongitude); var latRef = GetExifDataFromTag <string>(profile, ExifTag.GPSLatitudeRef); var lngRef = GetExifDataFromTag <string>(profile, ExifTag.GPSLongitudeRef); if (lat != null) { var latitude = lat[0] + lat[1] / 60.0 + lat[2] / 3600.0; if (latRef == "S") { latitude = -latitude; } var longitude = lng[0] + lng[1] / 60.0 + lng[2] / 3600.0; if (lngRef == "W") { longitude = -longitude; } exif.Latitude = latitude; exif.Longitude = longitude; exif.Location = SetLocationDetails(latitude, longitude); } }
public static RotateFlipType CorrectImageRotation(ref Stream stream, ExifData exif) { if (exif.OriginalOrientation == 0) { return(RotateFlipType.RotateNoneFlipNone); } var flip = OrientationToFlipType(exif.OriginalOrientation); if (flip == RotateFlipType.RotateNoneFlipNone) { return(RotateFlipType.RotateNoneFlipNone); } stream.Seek(0, SeekOrigin.Begin); var image = new Bitmap(stream); stream.Close(); image.RotateFlip(flip); stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); stream.Seek(0, SeekOrigin.Begin); exif.Width = image.Width; exif.Height = image.Height; exif.AspectRatio = image.Width / (double)image.Height; exif.Orientation = image.Width == image.Height ? "square" : (image.Width > image.Height ? "landscape" : "portrait"); return(flip); }
public static void Run() { //ExStart:ReadSpecificEXIFTagsInformation // The path to the documents directory. string dataDir = RunExamples.GetDataDir_JPEG(); Console.WriteLine("Running example ReadSpecificEXIFTagsInformation"); // Load an image using the factory method Load exposed by Image class using (Image image = Image.Load(dataDir + "aspose-logo.jpg")) { // Initialize an object of ExifData and fill it will image's EXIF information ExifData exif = ((JpegImage)image).ExifData; // Check if image has any EXIF entries defined and Display a few EXIF entries if (exif != null) { Console.WriteLine("Exif WhiteBalance: " + exif.WhiteBalance); Console.WriteLine("Exif PixelXDimension: " + exif.PixelXDimension); Console.WriteLine("Exif PixelYDimension: " + exif.PixelYDimension); Console.WriteLine("Exif ISOSpeed: " + exif.ISOSpeed); Console.WriteLine("Exif FocalLength: " + exif.FocalLength); } } Console.WriteLine("Finished example ReadSpecificEXIFTagsInformation"); //ExEnd:ReadSpecificEXIFTagsInformation }
public ExifData GetExifData(string filename) { using (var logger = _logger.Block()) { while (true) { try { // create the object to return var exifData = new ExifData(); logger.Trace($@"Opening ""{filename}""..."); using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { var bitmapSource = BitmapFrame.Create(fs, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None); if (!(bitmapSource.Metadata is BitmapMetadata bitmapMetadata)) { return(exifData); } // try and parse the date exifData.DateTaken = !DateTime.TryParse(bitmapMetadata.DateTaken, out var dateTaken) ? bitmapMetadata.DateTaken : dateTaken.Date.ToString(_shortDateFormat); // is there a latitude on the image exifData.Latitude = GetLatitude(bitmapMetadata); if (exifData.Latitude.HasValue) { exifData.Longitude = GetLongitude(bitmapMetadata); } try { // is there a title on the image? exifData.Title = bitmapMetadata.Title; } catch (NotSupportedException) { // ignore this exception } } return(exifData); } catch (IOException ex) { // check that this is a locked message if (!Regex.IsMatch(ex.Message, LockedPattern, RegexOptions.IgnoreCase)) { throw; } // give the file time to be released Thread.Sleep(500); } } } }
protected override void Serialize(Stream output, ExifData exifData) { var serializer = new DataContractSerializer(typeof(ExifData)); var writer = XmlWriter.Create(output); serializer.WriteObject(writer, exifData); writer.Flush(); }
bool MakeExifNode (TreeIter parent, TreeIter iter, ExifData ed, ExifTag tag) { string val = ed.Lookup (tag); if (val == null || val == "") return false; MakeNode (parent, out iter, ExifUtil.GetTagTitle (tag) + ":", ed.Lookup (tag)); return true; }
protected override void Serialize(Stream output, ExifData exifData) { if (output == null) { throw new ArgumentNullException("output"); } var serializer = new DataContractJsonSerializer(typeof(ExifData)); serializer.WriteObject(output, exifData); }
public static ExposureInfo GetExposureInfo(string path) { Exif.ExifData exif_data = new Exif.ExifData (path); #if UNSED_CODE MakerType maker = MakerType.Unknown; string maker_tag_value = exif_data.LookupString (ExifTag.Make); if (maker_tag_value != null) { if (maker_tag_value.ToLower () == "nikon") maker = MakerType.Nikon; else if (maker_tag_value.ToLower () == "canon") maker = MakerType.Canon; } #endif ExposureInfo info = new ExposureInfo (); info.ApertureValue = exif_data.LookupFirstValue (Exif.Tag.ApertureValue); info.ExposureTime = exif_data.LookupFirstValue (Exif.Tag.ExposureTime); info.DateTime = exif_data.LookupFirstValue (Exif.Tag.DateTimeOriginal); info.IsoSpeed = exif_data.LookupFirstValue (Exif.Tag.ISOSpeedRatings); // FIXME not sure why, this doesn't work. #if BROKEN_CODE // Use the maker note to figure out the ISO speed rating if it's not in the standard spot. if (info.IsoSpeed == null && exif_data.LookupData (ExifTag.MakerNote) != null) { switch (maker) { case MakerType.Canon: byte [] maker_note = exif_data.LookupData (ExifTag.MakerNote); ExifData maker_ifd = new ExifData (maker_note_copy, (uint) maker_note_copy.Length); byte [] data = maker_ifd.LookupData ((ExifTag) 0x1); if (data.Length > 0x10) { switch (data [0x10]) { case 0xf: info.IsoSpeed = "AUTO"; break; case 0x10: info.IsoSpeed = "ISO 50"; break; case 0x11: info.IsoSpeed = "ISO 100"; break; case 0x12: info.IsoSpeed = "ISO 200"; break; case 0x13: info.IsoSpeed = "ISO 400"; break; case 0x14: info.IsoSpeed = "ISO 800"; break; case 0x15: info.IsoSpeed = "ISO 1600"; break; case 0x16: info.IsoSpeed = "ISO 3200"; break; } } break; // FIXME: Add support for other MakerNotes, see: // http://www.fifi.org/doc/jhead/exif-e.html#APP1 } } #endif return info; }
private static void Main(string[] args) { // Reading EXIF data from a file (image001.jpg is part of the Demo project) ExifData exif = new ExifData("image001.jpg"); Console.WriteLine("Orientation: " + exif.Orientation); Console.WriteLine("Photo Taken: " + exif.DateTimeOriginal.ToString()); Console.WriteLine("Camera Model: " + exif.CameraModel); Console.WriteLine("Exposure Program: " + exif.ExposureProgram.ToString()); Console.ReadKey(false); }
bool MakeExifNode(TreeIter parent, TreeIter iter, ExifData ed, ExifTag tag) { string val = ed.Lookup(tag); if (val == null || val == "") { return(false); } MakeNode(parent, out iter, ExifUtil.GetTagTitle(tag) + ":", ed.Lookup(tag)); return(true); }
private static void GetRequiredExifData(MagickImage image, ExifData exif) { exif.Width = image.Width; exif.Height = image.Height; exif.AspectRatio = image.Width / (double)image.Height; exif.Orientation = image.Width == image.Height ? "square" : (image.Width > image.Height ? "landscape" : "portrait"); if (string.IsNullOrEmpty(exif.Title)) { exif.Title = "Untitled"; } }
public static int Main (String [] args) { if (args.Length != 1) { Console.WriteLine ("Usage : text-exif [filename]"); return 1; } string filename = args [0]; ExifData ed = new ExifData (filename); ed.Assemble (); return 0; }
int[] GetImageDimensions(string imagefile) { int[] wh = new int[2]; bool found_exif_data = false; using (ExifData ed = new ExifData(imagefile)) { string sw, sh; sw = ed.Lookup(ExifTag.PixelXDimension); sh = ed.Lookup(ExifTag.PixelYDimension); if (sw == null || sw == "") { sw = ed.Lookup(ExifTag.ImageWidth); sh = ed.Lookup(ExifTag.ImageLength); } if (sw != null && sw != "") { wh[0] = Convert.ToInt32(sw); wh[1] = Convert.ToInt32(sh); found_exif_data = true; } } if (!found_exif_data) { #if SLOW_WH_DISCOVERY Process proc = new Process(); proc.StartInfo.FileName = "identify"; proc.StartInfo.Arguments = "-format \"%w %h\" " + imagefile; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); string procout = proc.StandardOutput.ReadToEnd(); proc.WaitForExit(); int result = proc.ExitCode; proc.Close(); char[] splitchars = { ' ' }; string[] whstring = procout.Split(splitchars); wh[0] = Convert.ToInt32(whstring[0]); wh[1] = Convert.ToInt32(whstring[1]); #else wh[0] = 0; wh[1] = 1; #endif } return(wh); }
public static int Main(String [] args) { if (args.Length != 1) { Console.WriteLine("Usage : text-exif [filename]"); return(1); } string filename = args [0]; ExifData ed = new ExifData(filename); ed.Assemble(); return(0); }
int[] GetImageDimensions (string imagefile) { int[] wh = new int[2]; bool found_exif_data = false; using (ExifData ed = new ExifData (imagefile)) { string sw, sh; sw = ed.Lookup (ExifTag.PixelXDimension); sh = ed.Lookup (ExifTag.PixelYDimension); if (sw == null || sw == "") { sw = ed.Lookup (ExifTag.ImageWidth); sh = ed.Lookup (ExifTag.ImageLength); } if (sw != null && sw != "") { wh[0] = Convert.ToInt32 (sw); wh[1] = Convert.ToInt32 (sh); found_exif_data = true; } } if (!found_exif_data) { #if SLOW_WH_DISCOVERY Process proc = new Process (); proc.StartInfo.FileName = "identify"; proc.StartInfo.Arguments = "-format \"%w %h\" " + imagefile; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start (); string procout = proc.StandardOutput.ReadToEnd (); proc.WaitForExit (); int result = proc.ExitCode; proc.Close (); char[] splitchars = {' '}; string[] whstring = procout.Split(splitchars); wh[0] = Convert.ToInt32 (whstring[0]); wh[1] = Convert.ToInt32 (whstring[1]); #else wh[0] = 0; wh[1] = 1; #endif } return wh; }
public void UpdateInfo(string path) { FileInfo fi = new FileInfo(path); store.SetValue(iter_file_name, 1, new GLib.Value(fi.Name)); store.SetValue(iter_file_size, 1, new GLib.Value(String.Format("{0:0,0}", fi.Length))); store.SetValue(iter_file_date, 1, new GLib.Value(File.GetLastWriteTime(path).ToString())); using (ExifData ed = new ExifData(path)){ int i = 0; foreach (object v in det_values) { store.SetValue(det_iter [i], 1, new GLib.Value(ed.Lookup((ExifTag)v))); i++; } } }
private void CreateExifData() { IsProcessing = true; Task.Factory.StartNew(() => { var items = new List <ExifData>(); var files = Directory.EnumerateFiles(folderPath, "*.jpg"); foreach (var file in files) { string fileName = Path.GetFileName(file); Image image = new Bitmap(file); var props = new ExifData(fileName, image); items.Add(props); } Execute.OnUIThread(() => ExifCollectionViewSource.Source = items); Execute.OnUIThread(() => IsProcessing = false); }); }
public void MakeThumbnail(ThumbnailerInfo tinfo) { // first check and see if there's a thumbnail in the exif #if USE_EXIF_THUMBS try { using (ExifData ed = new ExifData(tinfo.source)) { byte [] thumbData = ed.Data; if (thumbData.Length > 0) { Console.WriteLine("Trying to write " + tinfo.target); // exif contains a thumbnail, so spit it out FileStream fs = File.Create(tinfo.target, Math.Min(thumbData.Length, 4096)); fs.Write(thumbData, 0, thumbData.Length); fs.Close(); tinfo.thumbnail = null; tinfo.status = ThumbnailStatus.OK; return; } } } catch { Console.WriteLine("** exif died for " + tinfo.target); } #endif // if not found, use GdkPixbuf to scale try { using (Pixbuf image_pixbuf = new Pixbuf(tinfo.source)) { int thumb_width; int thumb_height; if (image_pixbuf.Width > image_pixbuf.Height) { thumb_width = 160; thumb_height = (int)(160 * ((float)image_pixbuf.Height / (float)image_pixbuf.Width)); } else { thumb_height = 160; thumb_width = (int)(160 * ((float)image_pixbuf.Width / (float)image_pixbuf.Height)); } Pixbuf thumb_pixbuf = image_pixbuf.ScaleSimple(thumb_width, thumb_height, InterpType.Tiles); // this will need to be fixed when this particular Gdk.Pixbuf function gets // better bindings try { tinfo.thumbnail = thumb_pixbuf; if (tinfo.target.EndsWith("png")) { thumb_pixbuf.Savev(tinfo.target, "png", null, null); } else { thumb_pixbuf.Savev(tinfo.target, "jpeg", null, null); } } catch (GLib.GException e) { tinfo.status = ThumbnailStatus.UnableToCreate; return; } tinfo.status = ThumbnailStatus.OK; } } catch (GLib.GException e) { tinfo.status = ThumbnailStatus.InvalidSource; return; } }
void UpdateForFile (string filename) { this.Clear (); TreeIter first_level_iter = new TreeIter (); using (ExifData ed = new ExifData (filename)) { TreeIter child_iter; string s; FileInfo fi = new FileInfo (filename); MakeNode (out first_level_iter, "File:", fi.Name); MakeNode (out first_level_iter, "Date:", ed.Lookup (ExifTag.DateTime)); string ws = ed.Lookup (ExifTag.PixelXDimension); string hs = ed.Lookup (ExifTag.PixelYDimension); if (ws == null || ws == "") { ws = ed.Lookup (ExifTag.ImageWidth); hs = ed.Lookup (ExifTag.ImageLength); } if (ws != null && ws != "") { int width; int height; try { width = Convert.ToInt32 (ws); height = Convert.ToInt32 (hs); } catch { width = 0; height = 0; } if (width != 0) MakeNode (out first_level_iter, "Dimensions:", width + "x" + height); else MakeNode (out first_level_iter, "Dimensions:", "unknown"); } MakeNode (out first_level_iter, "Size:", String.Format ("{0:0,0}", fi.Length) + " bytes"); this.Append (out first_level_iter); this.SetValue (first_level_iter, 0, new GLib.Value ("<b>Exposure</b>")); child_iter = new TreeIter (); if (!MakeExifNode (first_level_iter, child_iter, ed, ExifTag.ApertureValue)) MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FNumber); if (!MakeExifNode (first_level_iter, child_iter, ed, ExifTag.ShutterSpeedValue)) MakeExifNode (first_level_iter, child_iter, ed, ExifTag.ExposureTime); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FocalLength); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.ISOSpeedRatings); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.MeteringMode); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.ExposureBiasValue); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FlashEnergy); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.WhiteBalance); // this.Append (out first_level_iter); // this.SetValue (first_level_iter, 0, new GLib.Value ("<b>Image</b>")); // child_iter = new TreeIter (); this.Append (out first_level_iter); this.SetValue (first_level_iter, 0, new GLib.Value ("<b>Equipment</b>")); child_iter = new TreeIter (); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.Make); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.Model); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.Software); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.ExifVersion); MakeExifNode (first_level_iter, child_iter, ed, ExifTag.SensingMethod); // MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FocalPlaneXResolution); // MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FocalPlaneYResolution); // MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FocalPlaneResolutionUnit); } my_view.ExpandAll (); }
private static ExifData ProcessExifTag(byte[] data, int position, Endianess endianess, IFDType ifdType) { var result = new ExifData { IFDType = ifdType }; if (ifdType == IFDType.IFD_GPS) { result.GPSTag = data.ReadGPSType(position, endianess); } else { result.ExifTag = data.ReadExifType(position, endianess); } var dataType = data.ReadUShort(position + 2, endianess); result.ValueType = (ExifValueType)dataType; var componentCount = data.ReadUInt(position + 4, endianess); int offset; switch (result.ValueType) { case ExifValueType.UnsignedByte: // unsigned byte, 1 byte / component if (componentCount > 4) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } { var lst = new List <byte>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadByte(offset + i)); } result.Value = String.Join(", ", lst.Select(x => x.ToString(CultureInfo.InvariantCulture))); } break; case ExifValueType.ASCIIString: // ascii strings, 1 byte / component if (componentCount > 4) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } result.Value = data.ReadString(offset, componentCount); break; case ExifValueType.UnsignedShort: // unsigned short, 2 bytes / component if (componentCount > 2) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } { var lst = new List <ushort>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadUShort(offset + (i * 2), endianess)); } result.Value = String.Join(", ", lst.Select(x => x.ToString(CultureInfo.InvariantCulture))); } break; case ExifValueType.UnsignedLong: // unsigned long, 4 bytes / component if (componentCount > 1) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } { var lst = new List <uint>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadUInt(offset + (i * 4), endianess)); } result.Value = String.Join(", ", lst.Select(x => x.ToString(CultureInfo.InvariantCulture))); } break; case ExifValueType.UnsignedRational: // unsigned rational, 8 bytes / component offset = (int)data.ReadUInt(position + 8, endianess); { var lst = new List <string>(); for (var i = 0; i < componentCount; i++) { var numerator = data.ReadUInt(offset + (i * 8), endianess); var denominator = data.ReadUInt(offset + (i * 8) + 4, endianess); lst.Add(String.Format("{0}/{1}", numerator, denominator)); } result.Value = String.Join(", ", lst); } break; case ExifValueType.SignedByte: // signed byte, 1 byte / component if (componentCount > 4) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } { var lst = new List <sbyte>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadSByte(offset + i)); } result.Value = String.Join(", ", lst.Select(x => x.ToString(CultureInfo.InvariantCulture))); } break; case ExifValueType.Undefined: // undefined switch (result.ExifTag) { case ExifTag.ComponentConfiguration: result.Value = String.Format("{0}, {1}, {2}, {3}", data.ReadByte(position + 8), data.ReadByte(position + 9), data.ReadByte(position + 10), data.ReadByte(position + 11)); break; case ExifTag.ExifVersion: result.Value = data.ReadString(position + 8, 4); break; default: { if (componentCount > 4) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } var lst = new List <byte>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadByte(offset + i)); } result.Value = String.Join(", ", lst.Select(x => x.ToString(CultureInfo.InvariantCulture))); } break; } break; case ExifValueType.SignedShort: // signed short, 2 bytes / component if (componentCount > 2) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } { var lst = new List <short>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadShort(offset + (i * 2), endianess)); } result.Value = String.Join(", ", lst.Select(x => x.ToString(CultureInfo.InvariantCulture))); } break; case ExifValueType.SignedLong: // signed long, 4 bytes / component if (componentCount > 1) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } { var lst = new List <int>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadInt(offset + (i * 4), endianess)); } result.Value = String.Join(", ", lst.Select(x => x.ToString(CultureInfo.InvariantCulture))); } break; case ExifValueType.SignedRational: // signed rational, 8 bytes / component offset = (int)data.ReadUInt(position + 8, endianess); { var lst = new List <string>(); for (var i = 0; i < componentCount; i++) { var numerator = data.ReadInt(offset + (i * 8), endianess); var denominator = data.ReadInt(offset + (i * 8) + 4, endianess); lst.Add(String.Format("{0}/{1}", numerator, denominator)); } result.Value = String.Join(", ", lst); } break; case ExifValueType.Single: // single float, 4 bytes / component if (componentCount > 1) { offset = (int)data.ReadUInt(position + 8, endianess); } else { offset = position + 8; } { var lst = new List <float>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadSingle(offset + (i * 4), endianess)); } result.Value = String.Join(", ", lst.Select(x => x.ToString(CultureInfo.InvariantCulture))); } break; case ExifValueType.Double: // double float, 8 bytes / component offset = (int)data.ReadUInt(position + 8, endianess); { var lst = new List <double>(); for (var i = 0; i < componentCount; i++) { lst.Add(data.ReadDouble(offset + (i * 4), endianess)); } result.Value = String.Join(", ", lst); } break; } return(result); }
public void MakeThumbnail (ThumbnailerInfo tinfo) { // first check and see if there's a thumbnail in the exif #if USE_EXIF_THUMBS try { using (ExifData ed = new ExifData (tinfo.source)) { byte [] thumbData = ed.Data; if (thumbData.Length > 0) { Console.WriteLine ("Trying to write " + tinfo.target); // exif contains a thumbnail, so spit it out FileStream fs = File.Create (tinfo.target, Math.Min (thumbData.Length, 4096)); fs.Write (thumbData, 0, thumbData.Length); fs.Close (); tinfo.thumbnail = null; tinfo.status = ThumbnailStatus.OK; return; } } } catch { Console.WriteLine ("** exif died for " + tinfo.target); } #endif // if not found, use GdkPixbuf to scale try { using (Pixbuf image_pixbuf = new Pixbuf (tinfo.source)) { int thumb_width; int thumb_height; if (image_pixbuf.Width > image_pixbuf.Height) { thumb_width = 160; thumb_height = (int) (160 * ((float) image_pixbuf.Height / (float) image_pixbuf.Width)); } else { thumb_height = 160; thumb_width = (int) (160 * ((float) image_pixbuf.Width / (float) image_pixbuf.Height)); } Pixbuf thumb_pixbuf = image_pixbuf.ScaleSimple (thumb_width, thumb_height, InterpType.Tiles); // this will need to be fixed when this particular Gdk.Pixbuf function gets // better bindings try { tinfo.thumbnail = thumb_pixbuf; if (tinfo.target.EndsWith ("png")) { thumb_pixbuf.Savev (tinfo.target, "png", null, null); } else { thumb_pixbuf.Savev (tinfo.target, "jpeg", null, null); } } catch (GLib.GException e) { tinfo.status = ThumbnailStatus.UnableToCreate; return; } tinfo.status = ThumbnailStatus.OK; } } catch (GLib.GException e) { tinfo.status = ThumbnailStatus.InvalidSource; return; } }
void UpdateForFile(string filename) { this.Clear(); TreeIter first_level_iter = new TreeIter(); using (ExifData ed = new ExifData(filename)) { TreeIter child_iter; string s; FileInfo fi = new FileInfo(filename); MakeNode(out first_level_iter, "File:", fi.Name); MakeNode(out first_level_iter, "Date:", ed.Lookup(ExifTag.DateTime)); string ws = ed.Lookup(ExifTag.PixelXDimension); string hs = ed.Lookup(ExifTag.PixelYDimension); if (ws == null || ws == "") { ws = ed.Lookup(ExifTag.ImageWidth); hs = ed.Lookup(ExifTag.ImageLength); } if (ws != null && ws != "") { int width; int height; try { width = Convert.ToInt32(ws); height = Convert.ToInt32(hs); } catch { width = 0; height = 0; } if (width != 0) { MakeNode(out first_level_iter, "Dimensions:", width + "x" + height); } else { MakeNode(out first_level_iter, "Dimensions:", "unknown"); } } MakeNode(out first_level_iter, "Size:", String.Format("{0:0,0}", fi.Length) + " bytes"); this.Append(out first_level_iter); this.SetValue(first_level_iter, 0, new GLib.Value("<b>Exposure</b>")); child_iter = new TreeIter(); if (!MakeExifNode(first_level_iter, child_iter, ed, ExifTag.ApertureValue)) { MakeExifNode(first_level_iter, child_iter, ed, ExifTag.FNumber); } if (!MakeExifNode(first_level_iter, child_iter, ed, ExifTag.ShutterSpeedValue)) { MakeExifNode(first_level_iter, child_iter, ed, ExifTag.ExposureTime); } MakeExifNode(first_level_iter, child_iter, ed, ExifTag.FocalLength); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.ISOSpeedRatings); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.MeteringMode); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.ExposureBiasValue); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.FlashEnergy); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.WhiteBalance); // this.Append (out first_level_iter); // this.SetValue (first_level_iter, 0, new GLib.Value ("<b>Image</b>")); // child_iter = new TreeIter (); this.Append(out first_level_iter); this.SetValue(first_level_iter, 0, new GLib.Value("<b>Equipment</b>")); child_iter = new TreeIter(); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.Make); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.Model); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.Software); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.ExifVersion); MakeExifNode(first_level_iter, child_iter, ed, ExifTag.SensingMethod); // MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FocalPlaneXResolution); // MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FocalPlaneYResolution); // MakeExifNode (first_level_iter, child_iter, ed, ExifTag.FocalPlaneResolutionUnit); } my_view.ExpandAll(); }
private static DateTime?GetDate(ExifData exif) { return(exif.Gps?.DateTimeStamp?.ToUniversalTime() ?? exif.ExifSubIfd?.DateTimeOriginal?.ToUniversalTime()); }
protected abstract void Serialize(Stream output, ExifData exifData);
public static MetaInformation ReadExifData(MemoryStream sourceStream) { sourceStream.Seek(0, SeekOrigin.Begin); using (var reader = new ExifReader(sourceStream)) { var meta = new MetaInformation(); var exif = new ExifData(); exif.Make = SetExifData <string>(reader, ExifTags.Make); exif.Model = SetExifData <string>(reader, ExifTags.Model); exif.CaptureDate = SetExifData <DateTime>(reader, ExifTags.DateTimeOriginal); exif.Description = SetExifData <string>(reader, ExifTags.ImageDescription); exif.Artist = SetExifData <string>(reader, ExifTags.Artist); exif.Copyright = SetExifData <string>(reader, ExifTags.Copyright); exif.Software = SetExifData <string>(reader, ExifTags.Software); exif.FocalLength = SetExifData <double>(reader, ExifTags.FocalLength); exif.FNumber = SetExifData <double>(reader, ExifTags.FNumber); exif.ApertureValue = SetExifData <double>(reader, ExifTags.ApertureValue); exif.MaxApertureValue = SetExifData <double>(reader, ExifTags.MaxApertureValue); exif.ExposureTime = SetExifData <double>(reader, ExifTags.ExposureTime); exif.ExposureBiasValue = SetExifData <double>(reader, ExifTags.ExposureBiasValue); exif.ExposureProgram = SetExifData <ushort>(reader, ExifTags.ExposureProgram); exif.ExposureMode = SetExifData <ushort>(reader, ExifTags.ExposureMode); exif.ISOSpeedRatings = SetExifData <ushort>(reader, ExifTags.ISOSpeedRatings); exif.MeteringMode = SetExifData <ushort>(reader, ExifTags.MeteringMode); double x = SetExifData <double>(reader, ExifTags.XResolution); double y = SetExifData <double>(reader, ExifTags.YResolution); exif.XResolution = x; exif.YResolution = y; exif.ResolutionUnit = SetExifData <ushort>(reader, ExifTags.ResolutionUnit); var image = new Bitmap(sourceStream); exif.Width = image.Width; exif.Height = image.Height; exif.AspectRatio = (double)image.Width / (double)image.Height; exif.Orientation = image.Width == image.Height ? "square" : (image.Width > image.Height ? "landscape" : "portrait"); double[] lat = SetExifData <double[]>(reader, ExifTags.GPSLatitude); double[] lng = SetExifData <double[]>(reader, ExifTags.GPSLongitude); string latRef = SetExifData <string>(reader, ExifTags.GPSLatitudeRef); string lngRef = SetExifData <string>(reader, ExifTags.GPSLongitudeRef); if (lat != null) { double latitude = 0; double longitude = 0; latitude = lat[0] + lat[1] / 60.0 + lat[2] / 3600.0; if (latRef == "S") { latitude = -latitude; } longitude = lng[0] + lng[1] / 60.0 + lng[2] / 3600.0; if (lngRef == "W") { longitude = -longitude; } exif.Latitude = latitude; exif.Longitude = longitude; } meta.Exif = exif; return(meta); } }
/// <summary> /// Liest die Exifdaten eines Bilder aus /// </summary> /// <param name="sourceStream">Das Bild als Memorysteam</param> /// <returns>Ein <see cref="ExifData"/>zurück </returns> public static ExifData ReadExifData(Stream sourceStream) { //Den Stream kopieren, damit der Reader ihn nicht verwirft var readerStream = new MemoryStream(); sourceStream.Seek(0, SeekOrigin.Begin); sourceStream.CopyTo(readerStream); readerStream.Seek(0, SeekOrigin.Begin); var magickImage = new MagickImage(readerStream); try { var exif = new ExifData(); var profile = magickImage.GetExifProfile(); var itpcProfile = magickImage.GetIptcProfile(); exif.Title = GetExifDataFromTag(itpcProfile, IptcTag.Title); exif.Make = GetExifDataFromTag <string>(profile, ExifTag.Make); exif.Model = GetExifDataFromTag <string>(profile, ExifTag.Model); exif.CaptureDate = GetExifDataFromTag <DateTime>(profile, ExifTag.DateTimeOriginal); exif.Description = GetExifDataFromTag <string>(profile, ExifTag.ImageDescription); exif.Artist = GetExifDataFromTag <string>(profile, ExifTag.Artist); exif.Copyright = GetExifDataFromTag <string>(profile, ExifTag.Copyright); exif.Software = GetExifDataFromTag <string>(profile, ExifTag.Software); exif.FocalLength = GetExifDataFromTag <double>(profile, ExifTag.FocalLength); exif.FNumber = GetExifDataFromTag <double>(profile, ExifTag.FNumber); exif.ApertureValue = GetExifDataFromTag <double>(profile, ExifTag.ApertureValue); exif.MaxApertureValue = GetExifDataFromTag <double>(profile, ExifTag.MaxApertureValue); exif.ExposureTime = GetExifDataFromTag <double>(profile, ExifTag.ExposureTime); exif.ExposureBiasValue = GetExifDataFromTag <double>(profile, ExifTag.ExposureBiasValue); exif.ExposureProgram = GetExifDataFromTag <ushort>(profile, ExifTag.ExposureProgram); exif.ExposureMode = GetExifDataFromTag <ushort>(profile, ExifTag.ExposureMode); exif.ISOSpeedRatings = GetExifDataFromTag <ushort>(profile, ExifTag.ISOSpeedRatings); exif.MeteringMode = GetExifDataFromTag <ushort>(profile, ExifTag.MeteringMode); exif.OriginalOrientation = GetExifDataFromTag <ushort>(profile, ExifTag.Orientation); if (itpcProfile != null) { var keyWords = itpcProfile.Values.Where(v => v.Tag == IptcTag.Keyword).ToList(); if (keyWords.Any()) { exif.Keywords = itpcProfile.Values.Where(v => v.Tag == IptcTag.Keyword) .Select(v => v.Value.ToString()) .ToList(); } } var x = GetExifDataFromTag <double>(profile, ExifTag.XResolution); var y = GetExifDataFromTag <double>(profile, ExifTag.YResolution); exif.XResolution = x; exif.YResolution = y; exif.ResolutionUnit = GetExifDataFromTag <ushort>(profile, ExifTag.ResolutionUnit); GetRequiredExifData(magickImage, exif); SetLocationData(profile, exif); return(exif); } catch { var data = new ExifData(); GetRequiredExifData(magickImage, data); return(data); } finally { magickImage.Dispose(); } }
static void Main(string [] args) { try { GLib.GType.Init (); GLib.LogFunc logFunc = new GLib.LogFunc (GLib.Log.PrintTraceLogFunction); GLib.Log.SetLogHandler ("GLib", GLib.LogLevelFlags.Critical, logFunc); GLib.Log.SetLogHandler ("GLib-GObject", GLib.LogLevelFlags.Critical, logFunc); GLib.Log.SetLogHandler ("GLib-GObject", GLib.LogLevelFlags.Warning, logFunc); if (args.Length != 1) { Console.WriteLine ("Usage: AddModel.exe file"); System.Environment.Exit (1); } // Container for exif metadata. This is an example of creating // exif metadata from scratch. If you want to add, modify, delete // metadata that exists in an image, start with ImageFactory.Open ExifData exifData = new ExifData (); //Add to the Exif data // This is the quickest way to add (simple) Exif data. If a metadatum for // a given key already exists, its value is overwritten. Otherwise a new // tag is added. exifData["Exif.Image.Model"] = "Test 1"; // AsciiValue exifData["Exif.Image.SamplesPerPixel"] = (UInt16)162; // UShortValue exifData["Exif.Image.XResolution"] = (Int32)(-2); // LongValue exifData["Exif.Image.YResolution"] = new Exiv2.Rational (-2, 3); // RationalValue exifData["Exif.Photo.DateTimeOriginal"] = "1999:12:31 23:59:59"; // AsciiValue Console.WriteLine ("Added a few tags the quick way."); // Modify Exif data // Since we know that the metadatum exists (or we don't mind creating a new // tag if it doesn't), we can simply do this: ExifDatum tag = exifData["Exif.Photo.DateTimeOriginal"] as ExifDatum; string date = tag.ToString (); date = "2000" + ((date.Length > 4) ? date.Substring (4) : null); tag.Value = date; Console.WriteLine ("Modified key '{0}', new value '{1}'", tag.Key, tag.ToString ()); // tag.setValue(date); // std::cout << "Modified key \"" << key // << "\", new value \"" << tag.value() << "\"\n"; // // // Alternatively, we can use findKey() // key = Exiv2::ExifKey("Exif.Image.PrimaryChromaticities"); // Exiv2::ExifData::iterator pos = exifData.findKey(key); // if (pos == exifData.end()) throw Exiv2::Error(1, "Key not found"); // // Get a pointer to a copy of the value // v = pos->getValue(); // // Downcast the Value pointer to its actual type // Exiv2::URationalValue* prv = dynamic_cast<Exiv2::URationalValue*>(v.release()); // if (prv == 0) throw Exiv2::Error(1, "Downcast failed"); // rv = Exiv2::URationalValue::AutoPtr(prv); // // Modify the value directly through the interface of URationalValue // rv->value_[2] = std::make_pair(88,77); // // Copy the modified value back to the metadatum // pos->setValue(rv.get()); // std::cout << "Modified key \"" << key // << "\", new value \"" << pos->value() << "\"\n"; exifData.Erase (new ExifKey("Exif.Image.XResolution")); //Finally, write the remaining data to the image file Exiv2.Image image = ImageFactory.Open (args [0]); image.ExifData = exifData; image.WriteMetadata (); } catch (GLib.GException e) { Console.WriteLine ("caught a GException {0}", e); } }
public void UpdateInfo (string path) { FileInfo fi = new FileInfo (path); store.SetValue (iter_file_name, 1, new GLib.Value (fi.Name)); store.SetValue (iter_file_size, 1, new GLib.Value (String.Format ("{0:0,0}", fi.Length))); store.SetValue (iter_file_date, 1, new GLib.Value (File.GetLastWriteTime (path).ToString ())); using (ExifData ed = new ExifData (path)){ int i = 0; foreach (object v in det_values){ store.SetValue (det_iter [i], 1, new GLib.Value (ed.Lookup ((ExifTag) v))); i++; } } }
public ImageInfo(string imagePath, string infoFile) { log.Info("ImageInfo(" + imagePath + ", " + infoFile + ")"); try { if (Directory.Exists(infoFile.Substring(0,infoFile.LastIndexOf("/"))) == false) Directory.CreateDirectory(infoFile.Substring(0,infoFile.LastIndexOf("/"))); if (System.IO.File.Exists(infoFile) == false || new FileInfo(imagePath).LastWriteTime > new FileInfo(infoFile).LastWriteTime) { log.Debug("...Creating new info file"); using (StreamWriter sw = new StreamWriter(infoFile)) { try { log.Debug("looking up exif data for: " + imagePath); ExifData exif_info = new ExifData(imagePath); //ExifContent content = exif_info.GetContents(Exif.Ifd.Zero); ExifContent[] contents = exif_info.GetContents(); foreach (ExifContent content in contents) { log.Debug("found " + content.GetEntries().Length + " exif tags in this ExifContent!"); foreach (ExifEntry entry in content.GetEntries()) { string tagName = entry.Name; string tagTitle = entry.Title; string tagValue = entry.Value; //int termix = tagValue.IndexOf('\0'); //tagValue = tagValue.Substring(0, termix < 0 ? tagValue.Length : termix); log.Debug("EXIF: " + tagTitle + " (" + tagName + ") = " + tagValue); sw.WriteLine( tagName + ": " + tagValue); // TODO: Change this to tagName (Update web.config) if (exifTags[tagTitle] == null) exifTags.Add(tagTitle, tagValue); } } if (exifTags["width"] == null || exifTags["height"] == null) { Bitmap bmp = new Bitmap(imagePath); if (exifTags["width"] == null) { log.Debug("No width found in exif info ... pulling from image."); //exifTags.Add("width", bmp.Width); this.Width = bmp.Width; sw.WriteLine( "width: " + bmp.Width); } if (exifTags["height"] == null) { log.Debug("No height found in exif info ... pulling from image."); //exifTags.Add("height", bmp.Height); this.Height = bmp.Height; sw.WriteLine( "height: " + bmp.Height); } } } catch (Exception ex) { if (ex is DllNotFoundException) log.Debug("EXIF not avaliable (libexif not installed)!", ex); else log.Debug("Error while reading exif data:\n " + ex.ToString()); Bitmap bmp = new Bitmap(imagePath); if (exifTags["width"] == null) { log.Debug("exif not avaliable.. saving from image."); this.Width = bmp.Width; sw.WriteLine( "width: " + bmp.Height); } if (exifTags["height"] == null) { log.Debug("exif not avaliable.. saving from image."); this.Height = bmp.Height; sw.WriteLine( "height: " + bmp.Height); } } sw.Close(); exifTags.Clear(); } } else { log.Debug("not creating new info file"); } using (StreamReader sr = new StreamReader(infoFile)) { string[] lines = sr.ReadToEnd().Split(Environment.NewLine.ToCharArray()); for (int x=0; x < lines.Length; x++) { string currentLine = lines[x]; if (currentLine.Length > 4 && currentLine.IndexOf(": ") > -1) { string propertyName = currentLine.Substring(0, currentLine.IndexOf(":")).ToLower(); string propertyValue = currentLine.Substring(propertyName.Length + 2); switch (propertyName.ToLower()) { case "width": this.Width = Convert.ToInt32(propertyValue); break; case "height": this.Height = Convert.ToInt32(propertyValue); break; default: if (exifTags[propertyName] == null) exifTags.Add(propertyName, propertyValue); break; } } } if (Width == 0) { log.Debug("Width not found in exif data!"); } if (Height == 0) { log.Debug("Height not found in exif data!"); } sr.Close(); } } catch (Exception ex) { if (File.Exists (infoFile)) File.Delete (infoFile); log.Error("Exception in ImageInfo constructor!", ex); throw ex; } }