Esempio n. 1
0
        public ActionResult GetImageGPS(string Id)
        {
            using (Image_context db = new Image_context())
            {
                int id = Int32.Parse(Id);
                Image_base img = db.Images.SingleOrDefault(f => f.Id == id);
                StringBuilder sb = new StringBuilder();
                try
                {

                    using (var reader = new ExifReader(img.url))
                    {
                        object val;
                        reader.GetTagValue(ExifTags.GPSLatitudeRef, out val);
                        string gps = RenderTag(val);
                        reader.GetTagValue(ExifTags.GPSLatitude, out val);
                        gps = gps + " " + RenderTag(val);
                        reader.GetTagValue(ExifTags.GPSLongitudeRef, out val);
                        gps = gps + " " + RenderTag(val);
                        reader.GetTagValue(ExifTags.GPSLongitude, out val);
                        gps = gps + " " + RenderTag(val);
                        Response.Write(gps);
                    }
                }
                catch (Exception ex)
                {
                    var error = ex.Message.ToString();
                    Response.Write(null);
                }
            }
            return null;
        }
Esempio n. 2
0
        public static GpsCoordinates GetCoordinates(string imageFileName)
        {
            using (var reader = new ExifReader(imageFileName))
            {
                Double[] latitude, longitude;
                var latitudeRef = "";
                var longitudeRef = "";                

               if (reader.GetTagValue(ExifTags.GPSLatitude, out latitude)
                    && reader.GetTagValue(ExifTags.GPSLongitude, out longitude)
                    && reader.GetTagValue(ExifTags.GPSLatitudeRef, out latitudeRef)
                    && reader.GetTagValue(ExifTags.GPSLongitudeRef, out longitudeRef))
                {
                    var longitudeTotal = longitude[0] + longitude[1] / 60 + longitude[2] / 3600;
                    var latitudeTotal = latitude[0] + latitude[1] / 60 + latitude[2] / 3600;

                    return new GpsCoordinates()
                    {
                        Latitude = (latitudeRef == "N" ? 1 : -1) * latitudeTotal,
                        Longitude = (longitudeRef == "E" ? 1 : -1) * longitudeTotal,
                    };
                }

                return new GpsCoordinates()
                {
                    Latitude = 0,
                    Longitude = 0,
                };
            }
        }
Esempio n. 3
0
        public ActionResult GetImageInfo(string Id)
        {
            using (Image_context db = new Image_context())
            {
                int id = Int32.Parse(Id);
                Image_base img = db.Images.SingleOrDefault(f => f.Id == id);
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("<h2>IMAGE INFO FROM DATABASE</h2>");
                sb.AppendFormat("<p>Load Date: {0}</p>", img.load_date);
                sb.AppendFormat("<p>Change Date: {0}</p>", img.change_date);
                try
                {
                    using (var reader = new ExifReader(img.url))
                    {
                        // Parse through all available fields and generate key-value labels
                        var props = Enum.GetValues(typeof(ExifTags)).Cast<ushort>().Select(tagID =>
                        {
                            object val;
                            if (reader.GetTagValue(tagID, out val))
                            {
                                // Special case - some doubles are encoded as TIFF rationals. These
                                // items can be retrieved as 2 element arrays of {numerator, denominator}
                                if (val is double)
                                {
                                    int[] rational;
                                    if (reader.GetTagValue(tagID, out rational))
                                        val = string.Format("{0} ({1}/{2})", val, rational[0], rational[1]);
                                }

                                return string.Format("<p>{0}: {1}</p>", Enum.GetName(typeof(ExifTags), tagID), RenderTag(val));
                            }

                            return null;

                        }).Where(x => x != null).ToArray();
                         var exifdata = string.Join("\r\n", props);
                         sb.AppendFormat("<h2>EXIF FROM IMAGE</h2>");
                         sb.AppendFormat("<p>{0}</p>", exifdata);
                    }
                }
                catch (Exception ex)
                {
                    // Something didn't work!
                    sb.AppendFormat("<h2>EXIF FROM IMAGE</h2>");
                    sb.AppendFormat("<p>{0}</p>", ex.Message.ToString());
                }
                Response.Write(sb.ToString());
                return null;

            }
        }
        public static DateTime? GetTakenTime(string fullName)
        {
            ExifReader reader = null;
            try
            {
                reader = new ExifReader(fullName);

                DateTime datePictureTaken;

                if (reader.GetTagValue(ExifTags.DateTimeOriginal, out datePictureTaken))
                {
                    Debug.WriteLine(string.Format("The picture was taken on {0}", datePictureTaken));
                    return datePictureTaken;
                }

                if (reader.GetTagValue(ExifTags.DateTimeDigitized, out datePictureTaken))
                {
                    Debug.WriteLine(string.Format("The picture was taken on {0}", datePictureTaken));
                    return datePictureTaken;
                }

                if (reader.GetTagValue(ExifTags.DateTime, out datePictureTaken))
                {
                    Debug.WriteLine(string.Format("The picture was taken on {0}", datePictureTaken));
                    return datePictureTaken;
                }

                if (reader.GetTagValue(ExifTags.GPSDateStamp, out datePictureTaken))
                {
                    Debug.WriteLine(string.Format("The picture was taken on {0}", datePictureTaken));
                    return datePictureTaken;
                }

                Debug.WriteLine(string.Format("The picture was taken on {0}", datePictureTaken));
                return datePictureTaken;
            }
            catch (Exception ex)
            {
                // Something didn't work!
                Debug.WriteLine(ex.ToString());
                //                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                if (reader != null)
                    reader.Dispose();
            }

            return null;
        }
Esempio n. 5
0
        public PhotoInfo ReadExif(string name)
        {
            PhotoInfo info = new PhotoInfo() { FileName = name };

            using (ExifReader reader = new ExifReader(name))
            {
                reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized, out info.DateTimeDigitized);

                reader.GetTagValue<string>(ExifTags.Model, out info.Model);

                if (info.Model == null)
                    info.Model = "Неизвестная модель";
            }

            return info;
        }
 public PictureInfo(string filename, Source source)
 {
     Name = filename;
     TimeShift = new TimeSpan();
     Source = source;
     using (var reader = new ExifReader(filename))
     {
         reader.GetTagValue<DateTime>(ExifTags.DateTimeOriginal, out time);
         string make, model;
         reader.GetTagValue<string>(ExifTags.Make, out make);
         reader.GetTagValue<string>(ExifTags.Model, out model);
         if (model != null || make != null)
         {
             Camera = String.Format("{0} {1}", make, model);
         }
     }
 }
 public virtual DateTime GetOriginalDateTime(string fileName)
 {
     DateTime result;
     using (var reader = new ExifReader(fileName)) {
         reader.GetTagValue(ExifTags.DateTimeOriginal, out result);
     }
     return result;
 }
Esempio n. 8
0
        private void ShowMap(String image)
        {
            try
            {
                var reader = new ExifLib.ExifReader(image);
                reader.GetTagValue(ExifTags.GPSLatitude, out double[] latit);
                reader.GetTagValue(ExifTags.GPSLongitude, out double[] longit);

                double latitreal  = latit[0] + latit[1] / 60f + latit[2] / 3600f;
                double longitreal = longit[0] + longit[1] / 60f + longit[2] / 3600f;

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "onload",
                                                    "initMap(" + latitreal.ToString() + "," + longitreal.ToString() + ");", true);
            }
            catch (System.NullReferenceException)
            {
            }
        }
Esempio n. 9
0
 private static void AssertStringValue(ExifReader reader, ExifTags tag, string expected)
 {
     string actual;
     if (!reader.GetTagValue(tag, out actual))
     {
         Assert.Fail("Tag '{0}' not found.", tag);
     }
     Assert.AreEqual(expected, actual, "Tag '{0}' value mismatch.");
 }
Esempio n. 10
0
        private static void GetExifData(Stream image, Photo data)
        {
            image.Seek(0, SeekOrigin.Begin);
            using (var reader = new ExifLib.ExifReader(image))
            {
                String timeString;
                if (reader.GetTagValue(ExifTags.DateTimeOriginal, out timeString))
                {
                    DateTime timeStamp;
                    if (DateTime.TryParseExact(timeString, "yyyy:MM:dd hh:mm:ss",
                                               CultureInfo.InvariantCulture,
                                               DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal,
                                               out timeStamp))
                    {
                        data.TimeStamp = timeStamp;
                    }
                }
                UInt16 hres, vres;
                object tagVal;
                if (reader.GetTagValue(ExifTags.PixelXDimension, out hres))
                {
                    data.Hres = (int)hres;
                }
                if (reader.GetTagValue(ExifTags.PixelYDimension, out vres))
                {
                    data.Vres = (int)vres;
                }
                if (reader.GetTagValue(ExifTags.FNumber, out tagVal))
                {
                    data.FStop = string.Format("f/{0:g2}", tagVal.ToString());
                }
                if (reader.GetTagValue(ExifTags.ExposureTime, out tagVal))
                {
                    data.ShutterSpeed = string.Format("1/{0:g0}", 1 / (double)tagVal);
                }
                if (reader.GetTagValue(ExifTags.ISOSpeedRatings, out tagVal))
                {
                    data.ISOspeed = (short)(ushort)tagVal;
                }
                if (reader.GetTagValue(ExifTags.FocalLength, out tagVal))
                {
                    data.FocalLength = (short)(double)tagVal;
                }

                if (reader.GetTagValue(ExifTags.SubsecTimeOriginal, out timeString))
                {
                    int msec;
                    if (int.TryParse(timeString, out msec))
                    {
                        data.TimeStamp += new TimeSpan(0, 0, 0, 0, msec);
                    }
                }
            }
        }
        private static double?GetCoordinate(this ExifLib.ExifReader reader, ExifTags type)
        {
            double[] coordinates;
            if (reader.GetTagValue(type, out coordinates))
            {
                return(ToDoubleCoordinates(coordinates));
            }

            return(null);
        }
Esempio n. 12
0
        internal static string Objektiv(string dateiname) {
            try {
                using (var exifReader = new ExifReader(dateiname)) {
                    string lensMake = "";
                    if (!exifReader.GetTagValue(    LensMakeTagId, out lensMake)) {
                        lensMake = "?";
                    }
                    string lensModel = "";
                    if (!exifReader.GetTagValue(LensModelTagId, out lensModel)) {
                        lensModel = "?";
                    }
                    return string.Format("{0} {1}", lensMake, lensModel);
                }

            }
            catch (ExifLibException) {
                return "";
            }
        }
Esempio n. 13
0
        private void GetExif(string image)
        {
            try
            {
                var reader = new ExifLib.ExifReader(image);


                reader.GetTagValue(ExifTags.ExifVersion, out byte[] version);
                reader.GetTagValue(ExifTags.DateTimeOriginal, out DateTime date);
                reader.GetTagValue(ExifTags.Model, out string model);
                reader.GetTagValue(ExifTags.Make, out string maker);
                reader.GetTagValue(ExifTags.ExposureTime, out double exptime);
                reader.GetTagValue(ExifTags.Compression, out UInt16 compression);



                Label1.Text = String.Concat("ExposureTime: ", exptime.ToString());
                Label2.Text = "ExifVersion: "; if (version != null)
                {
                    Label2.Text += System.Text.Encoding.UTF8.GetString(version);
                }
                Label3.Text = String.Concat("Data: ", String.Format("{0:dddd, MMMM d, yyyy}", date));
                Label4.Text = String.Concat("Model: ", model);
                Label5.Text = String.Concat("Maker: ", maker);
                Label6.Text = String.Concat("Compression:", EncodeCompression(compression));
                ShowMap(image);
            }
            catch (ExifLib.ExifLibException)
            {
                Label1.Text = "No EXIF info";
            }
        }
Esempio n. 14
0
        static bool GetExifDateTaken(string filePath, out DateTime dateTaken)
        {
            dateTaken = DateTime.MinValue;

            try
            {
                ExifReader rr = new ExifReader(filePath);
                return rr.GetTagValue(ExifTags.DateTime, out dateTaken);
            }
            catch (ExifLibException)
            {
                return false;
            }
        }
Esempio n. 15
0
        public DateTime GetEXIFDateTime(string imageFile)
        {
            DateTime retValue = new DateTime(1900, 1, 1);
            DateTime datePictureTaken;
            try // just getting the Standard EXIF data
            {
                using (ExifReader r = new ExifReader(imageFile))
                {
                    if (r.GetTagValue<DateTime>(ExifTags.DateTimeDigitized, out datePictureTaken))
                    {
                        retValue = datePictureTaken;
                    }
                }
            }
            catch (Exception) // if standard EXIF data cannot be found
            {
                try // getting the getting the RAW Exif data
                {
                    if (UseRawDate)
                    {
                        AppendToProgressLog("No standard EXIF data found in " + imageFile + " Attempting to get RAW EXIF date");
                        retValue = GetRawExifDate(imageFile);
                    }
                }
                catch (Exception) // if that still fails
                {
                    if (UseFileDateOnError) // use the file date if user has selected this option
                    {
                        try
                        {
                            AppendToProgressLog("No EXIF data found in " + imageFile + " attempting to get file date.");
                            datePictureTaken = File.GetLastWriteTime(imageFile);
                            retValue = datePictureTaken;
                        }
                        catch (Exception)
                        {
                            AppendToProgressLog("Unable to get file date. Cannot process this file");
                        } // we're dead in the water, just pass back the default date

                    }
                }
            }

            if (retValue==new DateTime(1900,1,1))
            {
                AppendToProgressLog("Unable to file a useable date. Cannot process this file.");
            }

            return retValue;
        }
Esempio n. 16
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                using (ExifReader reader = new ExifReader(path))
                {
                    properties = Enum.GetValues(typeof(ExifTags)).Cast<ushort>().Select(tagID =>
                    {
                        object val;
                        if (reader.GetTagValue(tagID, out val))
                        {
                        // Special case - some doubles are encoded as TIFF rationals. These
                        // items can be retrieved as 2 element arrays of {numerator, denominator}
                        if (val is double)
                            {
                                int[] rational;
                                if (reader.GetTagValue(tagID, out rational))
                                    val = string.Format("{0} ({1}/{2})", val, rational[0], rational[1]);
                            }

                            return string.Format("{0}: {1}", Enum.GetName(typeof(ExifTags), tagID), RenderTag(val));
                        }

                        return null;

                    }).Where(x => x != null).ToList();

                    PopulateGrid();
                    DisplayThumbnail(reader);
                }
            }
            catch (ExifLibException ex)
            {
                MessageBox.Show("Unable to load Exif data.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Close();
            }
        }
Esempio n. 17
0
        //Send list JSON objects with full image Exif information
        public List<JSONDataFormat> GetFullEXIF(ImageBase img)
        {
            List<JSONDataFormat> data = new List<JSONDataFormat>();
            try
            {
                using (var reader = new ExifReader(img.url))
                {
                    var props = Enum.GetValues(typeof(ExifTags)).Cast<ushort>().Select(tagID =>
                    {
                        object val;
                        if (reader.GetTagValue(tagID, out val))
                        {
                            if (val is double)
                            {
                                int[] rational;
                                if (reader.GetTagValue(tagID, out rational))
                                    val = string.Format("{0} ({1}/{2})", val, rational[0], rational[1]);
                            }
                            var inf = new JSONDataFormat();
                            inf.parameter = Enum.GetName(typeof(ExifTags), tagID);
                            inf.data = RenderTag(val);
                            return inf;
                        }

                        return null;

                    }).Where(x => x != null).ToList();
                    data.Add(new JSONDataFormat { parameter = "EXIF FROM IMAGE", data = null });
                    data.AddRange(props);
                }
            }
            catch (Exception ex)
            {
                data.Add(new JSONDataFormat { parameter = "EXIF FROM IMAGE", data = ex.Message.ToString() });
            }
            return data;
        }
Esempio n. 18
0
        //Gets metadata from picture source
        public static PictureProperties GetPictureMetadata(byte[] source)
        {
            try
            {
                DateTime datePictureTaken;
                object usingFlash;
                object focalLength;
                object ISO;
                using (Stream stream = new MemoryStream(source))
                {
                    using (ExifReader reader = new ExifReader(stream))
                    {
                        reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized,
                                                     out datePictureTaken);
                        reader.GetTagValue<object>(ExifTags.Flash,
                                                     out usingFlash);
                        reader.GetTagValue<object>(ExifTags.FocalLength,
                                                     out focalLength);
                        reader.GetTagValue<object>(ExifTags.ISOSpeedRatings,
                                                     out ISO);
                    }
                }

                return new PictureProperties()
                                                   {
                                                       ISO = Convert.ToSingle(ISO),
                                                       Flash = Convert.ToSingle(usingFlash)>0,
                                                       RecordingDate = datePictureTaken,
                                                       FocalDistance = Convert.ToSingle(focalLength)
                                                   };
            }
            catch (Exception)
            {
                return new PictureProperties();
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Constructor. 
        /// Loads the copyright and user comment for english language from EXIF info in picture
        /// </summary>
        /// <param name="fileName"></param>
        /// <exception cref="FileNotFoundException">Throws exception if file not found</exception>
        public Picture(string fileName)
        {
            if (File.Exists(fileName))
            {
                this.ID = -1;
                this.CopyrightText = string.Empty;
                this.Danish = string.Empty;
                this.English = string.Empty;
                this.German = string.Empty;

                try
                {
                    using (ExifReader reader = new ExifReader(fileName))
                    {
                        string outString = string.Empty;

                        if (reader.GetTagValue<string>(ExifTags.Copyright, out outString))
                        {
                            this.CopyrightText = outString;
                        }
                        if (reader.GetTagValue<string>(ExifTags.UserComment, out outString))
                        {
                            this.English = outString;
                        }
                    }
                }
                catch(ExifLibException exExif)
                {
                    if (OnExifError != null)
                        OnExifError(this, new Args.ExifErrorArgs(Args.ExifErrorArgs.ExifErrorTypes.MissingExif, exExif));
                }
                PictureData = Image.FromFile(fileName);
            }
            else
                throw new FileNotFoundException(string.Format("File not found: {0}", fileName), fileName);
        }
Esempio n. 20
0
 //Send list JSON objects with image GPS coordinats
 public List<JSONDataFormat> GetGPS(ImageBase img)
 {
     var gps = new List<JSONDataFormat>();
     try
     {
         using (var reader = new ExifReader(img.url))
         {
             object val;
             reader.GetTagValue(ExifTags.GPSLatitudeRef, out val);
             gps.Add(new JSONDataFormat { parameter = "GPSLatitudeRef", data = RenderTag(val) });
             reader.GetTagValue(ExifTags.GPSLatitude, out val);
             gps.Add(new JSONDataFormat { parameter = "GPSLatitude", data = RenderTag(val) });
             reader.GetTagValue(ExifTags.GPSLongitudeRef, out val);
             gps.Add(new JSONDataFormat { parameter = "GPSLongitudeRef", data = RenderTag(val) });
             reader.GetTagValue(ExifTags.GPSLongitude, out val);
             gps.Add(new JSONDataFormat { parameter = "GPSLongitude", data = RenderTag(val) });
         }
     }
     catch (Exception ex)
     {
         gps.Add(new JSONDataFormat { parameter = null, data = ex.Message.ToString() });
     }
     return gps;
 }
Esempio n. 21
0
        public static double[] GetLatLongFromImage(string imagePath)

        {
            ExifReader reader = new ExifReader(imagePath);

            // EXIF lat/long tags stored as [Degree, Minute, Second]
            double[] latitudeComponents;
            double[] longitudeComponents;

            string latitudeRef;  // "N" or "S" ("S" will be negative latitude)
            string longitudeRef; // "E" or "W" ("W" will be a negative longitude)

            if (reader.GetTagValue(ExifTags.GPSLatitude, out latitudeComponents) &&
                reader.GetTagValue(ExifTags.GPSLongitude, out longitudeComponents) &&
                reader.GetTagValue(ExifTags.GPSLatitudeRef, out latitudeRef) &&
                reader.GetTagValue(ExifTags.GPSLongitudeRef, out longitudeRef))
            {
                var latitude  = ConvertDegreeAngleToDouble(latitudeComponents[0], latitudeComponents[1], latitudeComponents[2], latitudeRef);
                var longitude = ConvertDegreeAngleToDouble(longitudeComponents[0], longitudeComponents[1], longitudeComponents[2], longitudeRef);
                return(new[] { latitude, longitude });
            }

            return(null);
        }
Esempio n. 22
0
        /// <summary>Returns DateTime from EXIF data or the FileInfo is there isn't one</summary>
        public static DateTime GetDateValueFromEXIF(string fileName)
        {
            try
            {
                using (ExifReader reader = new ExifReader(fileName))
                {
                    DateTime date;
                    if (reader.GetTagValue(ExifTags.DateTime, out date))
                        return date;
                }
            }
            catch (Exception) { }

            return new System.IO.FileInfo(fileName).LastWriteTime;
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            string folder = args.Length == 0 ? "." : args[0];

            foreach (string file in Directory.EnumerateFiles(folder, "*.jpg"))
            {
                DateTime dateTime;
                using (var reader = new ExifReader(file))
                {
                    if (!reader.GetTagValue(ExifTags.DateTimeOriginal, out dateTime)) continue;
                }

                string subFolder = Path.Combine(folder, dateTime.ToString("yyyy-MM-dd"));
                Directory.CreateDirectory(subFolder);
                File.Move(file, Path.Combine(subFolder, Path.GetFileName(file)));
            }
        }
        static void getImage(string path)
        {
            if(Path.GetExtension(path).ToLower()==".jpg")
            {
                using (ExifReader reader = new ExifReader(@path))
            {
                // Extract the tag data using the ExifTags enumeration
                DateTime datePictureTaken;
                if (reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized,
                                                out datePictureTaken))
                {
                    // Do whatever is required with the extracted information
                    copyImage(path, datePictureTaken);
                }
            }

            }
            else if(Path.GetExtension(path) == ".mp4")
            {
                string dateTaken = Path.GetFileName(path).Split(char.Parse("_"))[0];
                if (dateTaken.Length != 8)
                {
                    dateTaken = Path.GetFileName(path).Split(char.Parse("_"))[1];
                }
                dateTaken = dateTaken.Insert(4, "-").Insert(7, "-");
                copyImage(path, DateTime.Parse(dateTaken));
            }
            else if (Path.GetExtension(path).ToLower() == ".mov")
            {
                string dateTaken = Path.GetFileName(path).Split(char.Parse("_"))[0];
                if (dateTaken.Length != 8)
                {
                    dateTaken = Path.GetFileName(path).Split(char.Parse("_"))[1];
                }
                dateTaken = dateTaken.Insert(4, "-").Insert(7, "-");
                copyImage(path, DateTime.Parse(dateTaken));
            }
            else
            {
                unknownFiles += 1;
            }
        }
Esempio n. 25
0
        /// <summary>Returns Orientation from the EXIF data of a jpg.</summary>
        public static int GetDefaultRotationFromEXIF(string fileName)
        {
            if (!(GetExtension(fileName).Equals("jpg") || GetExtension(fileName).Equals("jpeg")))
                return 0;
            ushort orientation = 0;
            try
            {
                using (ExifReader reader = new ExifReader(fileName))
                {
                    if (!reader.GetTagValue(ExifTags.Orientation, out orientation))
                        return 0;

                    switch (orientation)
                    {
                        case 6: return 90;
                        case 3: return 180;
                        case 8: return 270;
                        default: return 0;
                    }
                }
            }
            catch (Exception) { }
            return 0;
        }
Esempio n. 26
0
        public void GetPhotoDetails(StorageFile file)
        {
            var task1 = getPhotoBasicPropertiesAsync(file);
            if (!task1.IsCompleted)
                task1.Wait();
            var fileProps = task1.Result;
            if (fileProps != null)
                FileSize = fileProps.Size / 1048576;               // konwersja do MB

            var task2 = getPhotoReadStreamAsync(file);
            if (!task2.IsCompleted)
                task2.Wait();
            var photoStream = task2.Result;

            using (var reader = new ExifReader(photoStream))
            {
                int pictureWidth;
                Width = reader.GetTagValue(ExifTags.PixelXDimension,
                    out pictureWidth) ? pictureWidth : 0;

                int pictureHeight;
                Height = reader.GetTagValue(ExifTags.PixelYDimension,
                    out pictureHeight) ? pictureHeight : 0;

                DateTime pictureTakenDate;
                if (reader.GetTagValue(ExifTags.DateTimeDigitized, out pictureTakenDate))
                    DateTaken = pictureTakenDate;
                else
                    DateTaken = reader.GetTagValue(ExifTags.DateTime,
                        out pictureTakenDate) ? pictureTakenDate : new DateTime(1900, 1, 1);

                double pictureLatitude;
                Latitude = reader.GetTagValue(ExifTags.GPSLatitude,
                    out pictureLatitude) ? pictureLatitude : 0;

                double pictureLongitude;
                Longitude = reader.GetTagValue(ExifTags.GPSLongitude,
                    out pictureLongitude) ? pictureLongitude : 0;
            }
        }
Esempio n. 27
0
        public static IBitmap Load(string filename, List<GLTextureStream.ImageMetaData> meta)
        {
            reattempt_load:
            try {
                if(filename.EndsWith(".im", StringComparison.OrdinalIgnoreCase))
                    return ImImageLoader.Load(filename);
            }
            catch(OutOfMemoryException) {
                GC.WaitForPendingFinalizers();
                goto reattempt_load;
            }

            Dictionary<ExifTags, GLTextureStream.ImageMetaData> exifdict = null;
            if(filename.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
                try
                {
                    using(ExifReader reader = new ExifReader(filename))
                    {
                        //foreach (ExifTags tag in Enum.GetValues(typeof(ExifTags)))
                        //	ReadExifValue(reader, tag, ref meta);

                        /*ReadExifRational(reader, ExifTags.ExposureTime, ref meta);
                        ReadExifRational(reader, ExifTags.FNumber, ref meta);
                        ReadExifShort(reader, ExifTags.ExposureProgram, ref meta);
                        ReadExifShort(reader, ExifTags.PhotographicSensitivity, ref meta);
                        ReadExifShort(reader, ExifTags.SensitivityType, ref meta);
                        ReadExifLong(reader, ExifTags.RecommendedExposureIndex, ref meta);
                        //ReadExifValue(reader, ExifTags.ExifVersion, ref meta); //undefined
                        ReadExifDate(reader, ExifTags.DateTimeOriginal, ref meta);
                        ReadExifDate(reader, ExifTags.DateTimeDigitized, ref meta);
                        //ReadExifValue(reader, ExifTags.ComponentsConfiguration, ref meta); //undefined
                        ReadExifRational(reader, ExifTags.CompressedBitsPerPixel, ref meta);
                        ReadExifRational(reader, ExifTags.BrightnessValue, ref meta);
                        ReadExifRational(reader, ExifTags.ExposureBiasValue, ref meta);
                        ReadExifRational(reader, ExifTags.MaxApertureValue, ref meta);
                        ReadExifShort(reader, ExifTags.MeteringMode, ref meta);
                        ReadExifShort(reader, ExifTags.LightSource, ref meta);
                        ReadExifShort(reader, ExifTags.Flash, ref meta);
                        ReadExifRational(reader, ExifTags.FocalLength, ref meta);
                        //ReadExifValue(reader, ExifTags.MakerNote, ref meta); //undefined
                        //ReadExifValue(reader, ExifTags.UserComment, ref meta); //comment
                        //ReadExifValue(reader, ExifTags.FlashpixVersion, ref meta); //undefined
                        ReadExifShort(reader, ExifTags.ColorSpace, ref meta);
                        ReadExifLong(reader, ExifTags.PixelXDimension, ref meta);
                        ReadExifLong(reader, ExifTags.PixelYDimension, ref meta);
                        ReadExifShort(reader, ExifTags.CustomRendered, ref meta);
                        ReadExifShort(reader, ExifTags.ExposureMode, ref meta);
                        ReadExifShort(reader, ExifTags.WhiteBalance, ref meta);
                        ReadExifRational(reader, ExifTags.DigitalZoomRatio, ref meta);
                        ReadExifShort(reader, ExifTags.FocalLengthIn35mmFilm, ref meta);
                        ReadExifShort(reader, ExifTags.SceneCaptureType, ref meta);
                        ReadExifShort(reader, ExifTags.Contrast, ref meta);
                        ReadExifShort(reader, ExifTags.Saturation, ref meta);
                        ReadExifShort(reader, ExifTags.Sharpness, ref meta);
                        ReadExifRational(reader, ExifTags.LensSpecification, ref meta);
                        ReadExifString(reader, ExifTags.LensModel, ref meta);*/

                        exifdict = new Dictionary<ExifTags,GLTextureStream.ImageMetaData>();
                        foreach (ExifTags tag in Enum.GetValues(typeof(ExifTags)))
                        {
                            if (exifdict.ContainsKey(tag))
                                continue;

                            object val;
                            if (reader.GetTagValue(tag, out val))
                            {
                                GLTextureStream.ImageMetaData m;
                                if (val is string)
                                    m = new GLTextureStream.ImageMetaData(tag.ToString(), 0.0f, (string)val);
                                else if (val is Array)
                                    continue; // Skip arrays
                                else
                                    m = new GLTextureStream.ImageMetaData(tag.ToString(), (float)(dynamic)val, val.ToString());

                                exifdict.Add(tag, m);
                                meta.Add(m);
                            }
                        }

                        /*int[] rational;
                        UInt16 word;
                        string str;
                        if(reader.GetTagValue(ExifTags.ApertureValue, out rational))
                        {
                            float value = (float)rational[0] / (float)rational[1];
                            meta.Add(new GLTextureStream.ImageMetaData("Aperture", value, value.ToString()));
                        }
                        if (reader.GetTagValue(ExifTags.BrightnessValue, out rational))
                        {
                            float value = (float)rational[0] / (float)rational[1];
                            meta.Add(new GLTextureStream.ImageMetaData("BrightnessValue", value, value.ToString()));
                        }
                        if (reader.GetTagValue(ExifTags.ExposureBiasValue, out rational))
                        {
                            float value = (float)rational[0] / (float)rational[1];
                            meta.Add(new GLTextureStream.ImageMetaData("ExposureBiasValue", value, value.ToString()));
                        }
                        if(reader.GetTagValue(ExifTags.PhotographicSensitivity, out word))
                        {
                            meta.Add(new GLTextureStream.ImageMetaData("ISO", (float)word, word.ToString()));
                        }
                        if(reader.GetTagValue(ExifTags.DateTime, out str))
                        {
                            DateTime date = DateTime.ParseExact(str, "yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
                            meta.Add(new GLTextureStream.ImageMetaData("Date", (float)date.Ticks, date.ToShortDateString()));
                        }*/

                        /*object obj;
                        if(reader.GetTagValue(ExifTags.PhotographicSensitivity, out obj))
                        {
                            Type type = obj.GetType();
                            while (type != null)
                            {
                                System.Console.WriteLine(type.Name);
                                type = type.BaseType;
                            }
                            int abc = 0;
                        }*/
                    }
                }
                catch
                {
                }

            reattempt_load2:
            try {
                Bitmap bmp = (Bitmap)Bitmap.FromFile(filename);
                GLTextureStream.ImageMetaData orientation;
                if (exifdict != null && exifdict.TryGetValue(ExifTags.Orientation, out orientation))
                {
                    switch((byte)orientation.value)
                    {
                        case 1: break;
                        case 2: bmp.RotateFlip(RotateFlipType.RotateNoneFlipX); break;
                        case 3: bmp.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
                        case 4: bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); break;
                        case 5: bmp.RotateFlip(RotateFlipType.Rotate90FlipX); break;
                        case 6: bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
                        case 7: bmp.RotateFlip(RotateFlipType.Rotate90FlipY); break;
                        case 8: bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
                    }
                }
                return new GdiBitmap(bmp);
            }
            catch(OutOfMemoryException) {
                GC.WaitForPendingFinalizers();
                goto reattempt_load2;
            }
            catch
            {
                /*int foo = filename.LastIndexOf('/');
                string newfilename = filename.Substring(0, foo + 1) + "damaged_" + filename.Substring(foo + 1);
                System.IO.File.Move(filename, newfilename);*/
                return null;
            }
            //return (Bitmap)Bitmap.FromFile(filename);
        }
Esempio n. 28
0
        private void ProcessOnFile(string sf, string extName)
        {
            // #1 Get MD5 Filename
            byte[] contents = File.ReadAllBytes(sf);
            byte[] output = md5.ComputeHash(contents);
            string newFileName = BitConverter.ToString(output).Replace("-", "") + extName;

            // #2 Get Taken DateTime
            string outDirName = "UNKNOWN";

            try
            {
                using (ExifReader reader = new ExifReader(sf))
                {
                    DateTime datePictureTaken;
                    if (reader.GetTagValue(ExifTags.DateTime, out datePictureTaken))
                    {
                        outDirName = string.Format("{0}-{1}", datePictureTaken.Year.ToString("D4"), datePictureTaken.Month.ToString("D2"));
                    }
                }

            }
            catch(Exception)
            {
            }

            // #3 Create directory if not exists
            Directory.CreateDirectory(this.targetPath + outDirName);
            File.WriteAllBytes(this.targetPath + outDirName + @"\" + newFileName + extName, contents);
            File.Delete(sf);
        }
Esempio n. 29
0
 private static void ReadExifRational(ExifReader reader, ExifTags tag, ref List<GLTextureStream.ImageMetaData> meta)
 {
     int[] rational;
     if (reader.GetTagValue(tag, out rational))
     {
         float value = (float)rational[0] / (float)rational[1];
         meta.Add(new GLTextureStream.ImageMetaData(tag.ToString(), value, value.ToString()));
     }
 }
 ushort GetExifOrientation(Stream imageStream)
 {
    try
    {
       ExifReader reader = new ExifReader(imageStream);
       ushort orientation;
       if (reader.GetTagValue(ExifTags.Orientation, out orientation))
       {
          System.Diagnostics.Debug.WriteLine("{0} {1}", orientation.GetType().Name, orientation.ToString());
          return orientation;
       }
    }
    catch (ExifLibException) { }
    return 1;
 }
Esempio n. 31
0
 static void ProcessImage(string image, string outpath)
 {
     var timage = image;
     try {
         DateTime datePicture = DateTime.MinValue;
         try {
             using (ExifReader reader = new ExifReader(timage)) {
                 DateTime datePictureTaken;
                 if (reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized, out datePictureTaken)) {
                     datePicture = datePictureTaken;
                 }
             }
         }
         catch (Exception) {
         }
         if (datePicture.Equals(DateTime.MinValue)) {
             var date = File.GetLastWriteTime(timage);
             Console.WriteLine("Can't determine date. " + timage + " Use file date: ( " + date.ToShortDateString() + " - " + date.ToShortTimeString() + " ) ? (y/n)");
             if (Console.ReadKey().KeyChar.ToString().ToUpper().Equals("Y")) {
                 datePicture = date;
                 Encoding _Encoding = Encoding.UTF8;
                 Image theImage = new Bitmap(image);
                 // 36867 = DateTimeOriginal
                 // 36868 = DateTimeDigitized
                 PropertyItem prop = theImage.PropertyItems[0];
                 SetProperty(ref prop, 36868, date.ToString("yyyy:MM:dd HH:mm:ss"));
                 theImage.SetPropertyItem(prop);
                 theImage.Save(timage + ".tmp");
                 timage = timage + ".tmp";
             }
         }
         if (!datePicture.Equals(DateTime.MinValue)) {
             int i = 1;
             while (File.Exists(DateToFile(outpath, datePicture, i))) {
                 i++;
             }
             //Console.WriteLine(DateToFile(outpath, datePicture, i));
             if (!Directory.Exists(DateToYear(outpath, datePicture))) {
                 Directory.CreateDirectory(DateToYear(outpath, datePicture));
             }
             if (!Directory.Exists(DateToYearMonth(outpath, datePicture))) {
                 Directory.CreateDirectory(DateToYearMonth(outpath, datePicture));
             }
             File.Move(timage, DateToFile(outpath, datePicture, i));
         }
     }
     catch (Exception e) {
         Console.WriteLine(timage + ": " + e.Message);
     }
 }
Esempio n. 32
0
        public static Position GetPositionFromImage(Stream imageStream)
        {
            var library = new MediaLibrary();
            var position = new Position();

            try
            {
                foreach (var picture in library.Pictures)
                {
                    if (picture.GetImage().Length == imageStream.Length)
                    {
                        var reader = new ExifReader(picture.GetImage());
                        double[] tmplat, tmplong;

                        if (reader.GetTagValue(ExifTags.GPSLatitude, out tmplat) &&
                            reader.GetTagValue(ExifTags.GPSLongitude, out tmplong))
                        {
                            position.Longitude = tmplong[0] + tmplong[1] / 60 +
                                tmplong[2] / (60 * 60);
                            position.Latitude = tmplat[0] + tmplat[1] / 60 +
                                tmplat[2] / (60 * 60);

                            string tmp;
                            if ((reader.GetTagValue(ExifTags.GPSLongitudeRef, out tmp) &&
                                tmp == "W"))
                            {
                                position.Longitude *= -1;
                            }

                            if ((reader.GetTagValue(ExifTags.GPSLatitudeRef, out tmp) &&
                                tmp == "S"))
                            {
                                position.Latitude *= -1;
                            }
                        }
                    }
                }
            }
            catch (ExifLibException ex)
            {
                if (ex.Message.Contains("Could not find Exif data block"))
                {
                    MessageBox.Show(AppResources.NoExifDataMessage, AppResources.NoExifDataMessageTitle, MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                BugSenseHandler.Instance.LogException(ex);
                MessageBox.Show(AppResources.GeneralErrorMessage, AppResources.GeneralErrorMessageTitle, MessageBoxButton.OK);
            }

            return position;
        }
Esempio n. 33
0
 private static void ReadExifShort(ExifReader reader, ExifTags tag, ref List<GLTextureStream.ImageMetaData> meta)
 {
     UInt16 num;
     if (reader.GetTagValue(tag, out num))
         meta.Add(new GLTextureStream.ImageMetaData(tag.ToString(), (float)num, num.ToString()));
 }
Esempio n. 34
0
 private static void ReadExifString(ExifReader reader, ExifTags tag, ref List<GLTextureStream.ImageMetaData> meta)
 {
     string str;
     if (reader.GetTagValue(tag, out str))
         meta.Add(new GLTextureStream.ImageMetaData(tag.ToString(), 0.0f, str));
 }
Esempio n. 35
0
 private static void ReadExifDate(ExifReader reader, ExifTags tag, ref List<GLTextureStream.ImageMetaData> meta)
 {
     string str;
     if (reader.GetTagValue(tag, out str))
     {
         DateTime date = DateTime.ParseExact(str, "yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
         meta.Add(new GLTextureStream.ImageMetaData(tag.ToString(), (float)date.Ticks, date.ToShortDateString()));
     }
 }
Esempio n. 36
0
        public ImageFile(string originPath)
        {
            try
            {
                ExifLib.ExifReader reader = new ExifLib.ExifReader(originPath);
                Image file = Image.FromFile(originPath);

                //Obtain ISO
                int    isos;
                object isos1;
                reader.GetTagValue <object>(ExifTags.PhotographicSensitivity, out isos1);
                isos = (int)Convert.ToUInt64(isos1);

                //focal
                object fl;
                reader.GetTagValue <object>(ExifTags.FocalLength, out fl);
                double focal;
                focal = Convert.ToDouble(fl);

                //exposure time
                double et;
                reader.GetTagValue(ExifTags.ExposureTime, out et);

                //MAKER
                string maker;
                reader.GetTagValue(ExifTags.Make, out maker);

                // DATETIME
                DateTime datatime;
                reader.GetTagValue(ExifTags.DateTime, out datatime);

                // Artist
                string artista;
                reader.GetTagValue(ExifTags.Artist, out artista);
                Artist = artista;

                //Copyright
                string copy;
                reader.GetTagValue(ExifTags.Copyright, out copy);

                //Camera  model
                string camera;
                reader.GetTagValue(ExifTags.Model, out camera);
                CameraModel = camera;

                //Aperture
                double apertures;
                reader.GetTagValue(ExifTags.FNumber, out apertures);

                // GPS
                var gps = ImageMetadataReader.ReadMetadata(originPath)
                          .OfType <GpsDirectory>()
                          .FirstOrDefault();
                if (gps != null)
                {
                    var    location = gps.GetGeoLocation();
                    double lat      = location.Latitude;
                    double lon      = location.Longitude;
                    string Location = string.Format("{0}\n{1}", lat, lon);
                    Geotag = Location;
                }
                else
                {
                    Geotag = null;
                }

                // SETTERS
                Height       = file.Height;
                Width        = file.Width;
                Iso          = isos;
                FocalLength  = (float)focal;
                ExposureTime = et;
                Make         = maker;
                DataTime     = datatime;
                Artist       = artista;
                Copyright    = copy;
                CameraModel  = camera;
                Aperture     = apertures;
            }
            catch (ExifLibException)
            {
                //IOUser.ConsoleError("\nThere is no EXIF information");
                //Thread.Sleep(1500);
            }

            Origin = originPath;
            Bpm    = new Bitmap(Origin);
        }