private bool GetExifDetails(string strPicture, ref int iRotation, ref string strDateTaken)
 {
     using (ExifMetadata extractor = new ExifMetadata())
     {
         ExifMetadata.Metadata metaData = extractor.GetExifMetadata(strPicture);
         try
         {
             string picExifDate = metaData.DatePictureTaken.DisplayValue;
             if (!String.IsNullOrEmpty(picExifDate))
             // If the image contains a valid exif date store it in the database, otherwise use the file date
             {
                 DateTime dat;
                 DateTime.TryParseExact(picExifDate, "G", Thread.CurrentThread.CurrentCulture, DateTimeStyles.None, out dat);
                 strDateTaken = dat.ToString("yyyy-MM-dd HH:mm:ss");
                 if (_useExif)
                 {
                     iRotation = EXIFOrientationToRotation(Convert.ToInt32(metaData.Orientation.Hex));
                 }
                 return(true);
             }
         }
         catch (FormatException ex)
         {
             Log.Error("PictureDatabaseSqlLite: Exif date conversion exception err:{0} stack:{1}", ex.Message,
                       ex.StackTrace);
         }
     }
     return(false);
 }
Пример #2
0
        public void GetDirectoryOfType_DirectoriesIsEmpty()
        {
            var directories = new List <Directory>();
            var metadata    = new ExifMetadata(null, directories);

            Assert.IsNull(metadata.GetDirectoryOfType <ExifIfd0Directory>());
        }
Пример #3
0
        /// <summary>
        /// Examines the exif metadata in am image and determines if the picture was rotated
        /// when it was taken. If the orientation is rotated, the image will be rotated to make it
        /// straight.
        /// </summary>
        /// <param name="image"></param>
        private static void FixImageOrientation(Bitmap image)
        {
            try
            {
                ExifOrientation orientation = ExifOrientation.Normal;
                try
                {
                    orientation = ExifMetadata.FromImage(image).Orientation;
                    if (orientation == ExifOrientation.Unknown)
                    {
                        orientation = ExifOrientation.Normal;
                    }
                }
                catch (Exception e) { Debug.Fail("Unexpected error getting image orientation", e.ToString()); }

                if (orientation == ExifOrientation.Rotate270CW)
                {
                    image.RotateFlip(RotateFlipType.Rotate90FlipXY);
                }
                else if (orientation == ExifOrientation.Rotate90CW)
                {
                    image.RotateFlip(RotateFlipType.Rotate270FlipXY);
                }
            }
            catch (Exception)
            {
                //image.PropertyItems will throw an exception if the image does not contain any exif data
            }
        }
        private void addExif(string fileName, uint width, uint height)
        {
            if (this.exif == null)
            {
                return;
            }

            ExifMetadata targetExif = new ExifMetadata(new Uri(fileName, UriKind.Absolute), false);

            targetExif.CameraModel           = this.exif.CameraModel;
            targetExif.ColorRepresentation   = this.exif.ColorRepresentation;
            targetExif.CreationSoftware      = "Sea Turtle Batch Image Processor";
            targetExif.DateImageTaken        = this.exif.DateImageTaken;
            targetExif.EquipmentManufacturer = this.exif.EquipmentManufacturer;
            targetExif.ExifVersion           = "2.2";
            targetExif.ExposureCompensation  = this.exif.ExposureCompensation;
            targetExif.ExposureMode          = this.exif.ExposureMode;
            targetExif.ExposureTime          = this.exif.ExposureTime;
            targetExif.FlashMode             = this.exif.FlashMode;
            targetExif.FocalLength           = this.exif.FocalLength;
            targetExif.Height = height;
            targetExif.HorizontalResolution = this.exif.HorizontalResolution;
            targetExif.IsoSpeed             = this.exif.IsoSpeed;
            targetExif.LensAperture         = this.exif.LensAperture;
            targetExif.LightSource          = this.exif.LightSource;
            targetExif.MeteringMode         = this.exif.MeteringMode;
            targetExif.VerticalResolution   = this.exif.VerticalResolution;
            targetExif.Width        = width;
            targetExif.LatitudeRaw  = this.exif.LatitudeRaw;
            targetExif.LongitudeRaw = this.exif.LongitudeRaw;
            targetExif.Altitude     = this.exif.Altitude;

            targetExif.SaveExif();
        }
Пример #5
0
        /// <summary>
        /// Removes GPS data and updates the image files in a directory
        /// </summary>
        public void RemoveExifLocation()
        {
            // Map directory in source folder
            string sourceDirectoryPath = Common.MapSourceFilePath(this.CleanerPath);

            // get array of file in specific directory
            string[] files = Directory.GetFiles(sourceDirectoryPath);

            foreach (string path in files)
            {
                // get EXIF data if exists
                ExifMetadata exifMetadata = (ExifMetadata)MetadataUtility.ExtractSpecificMetadata(path, MetadataType.EXIF);

                if (exifMetadata != null)
                {
                    ExifInfo exifInfo = exifMetadata.Data;

                    if (exifInfo.GPSData != null)
                    {
                        // set altitude, latitude and longitude to null values
                        exifInfo.GPSData.Altitude     = null;
                        exifInfo.GPSData.Latitude     = null;
                        exifInfo.GPSData.LatitudeRef  = null;
                        exifInfo.GPSData.Longitude    = null;
                        exifInfo.GPSData.LongitudeRef = null;
                    }

                    // and update file
                    MetadataUtility.UpdateMetadata(path, exifMetadata);
                }
            }
            Console.WriteLine("Press any key to exit.");
        }
Пример #6
0
        public void GetExifMetaDataTest()
        {
            ExifHelper   _exifHelper = new ExifHelper();
            string       _path       = string.Format(@"{0}\TestSource\WP_20150912_18_11_56_Pro.jpg", AppDomain.CurrentDomain.BaseDirectory);
            ExifMetadata _mateData   = _exifHelper.GetMetaData(_path);

            Assert.AreEqual("2015:09:12 18:11:56\0", _mateData.DatePictureTaken.DisplayValue);
        }
Пример #7
0
        private void Update()
        {
            if (m_pTexture != null)
            {
                m_pTexture.Dispose();
            }

            int iRotate = PictureDatabase.GetRotation(FileName);

            m_pTexture = Util.Picture.Load(FileName, iRotate, 1024, 1024, true, false, out m_iTextureWidth,
                                           out m_iTextureHeight);

            lblCameraModel.Label          = string.Empty;
            lblDateTakenLabel.Label       = string.Empty;
            lblEquipmentMake.Label        = string.Empty;
            lblExposureCompensation.Label = string.Empty;
            lblExposureTime.Label         = string.Empty;
            lblFlash.Label         = string.Empty;
            lblFstop.Label         = string.Empty;
            lblImgDimensions.Label = string.Empty;
            lblImgTitle.Label      = string.Empty;
            lblMeteringMode.Label  = string.Empty;
            lblResolutions.Label   = string.Empty;
            lblShutterSpeed.Label  = string.Empty;
            lblViewComments.Label  = string.Empty;

            using (ExifMetadata extractor = new ExifMetadata())
            {
                ExifMetadata.Metadata metaData = extractor.GetExifMetadata(FileName);

                lblCameraModel.Label          = metaData.CameraModel.DisplayValue;
                lblDateTakenLabel.Label       = metaData.DatePictureTaken.DisplayValue;
                lblEquipmentMake.Label        = metaData.EquipmentMake.DisplayValue;
                lblExposureCompensation.Label = metaData.ExposureCompensation.DisplayValue;
                lblExposureTime.Label         = metaData.ExposureTime.DisplayValue;
                lblFlash.Label         = metaData.Flash.DisplayValue;
                lblFstop.Label         = metaData.Fstop.DisplayValue;
                lblImgDimensions.Label = metaData.ImageDimensions.DisplayValue;
                lblImgTitle.Label      = Path.GetFileNameWithoutExtension(FileName);
                lblMeteringMode.Label  = metaData.MeteringMode.DisplayValue;
                lblResolutions.Label   = metaData.Resolution.DisplayValue;
                lblShutterSpeed.Label  = metaData.ShutterSpeed.DisplayValue;
                lblViewComments.Label  = metaData.ViewerComments.DisplayValue;

                imgPicture.IsVisible = false;
            }
            if (File.Exists(FileName))
            {
                GUIPropertyManager.SetProperty("#selectedthumb", FileName);
            }
            else
            {
                GUIPropertyManager.SetProperty("#selectedthumb", string.Empty);
            }
        }
Пример #8
0
        public void GetDirectoryOfType_CorrectDirectory()
        {
            var firstDir    = new ExifIfd0Directory();
            var secondDir   = new ExifThumbnailDirectory();
            var directories = new List <Directory> {
                firstDir, secondDir
            };
            var metadata = new ExifMetadata(null, directories);

            Assert.AreEqual(firstDir, metadata.GetDirectoryOfType <ExifIfd0Directory>());
        }
Пример #9
0
        /*private Dictionary<string, object> getExifMeta(string imagePath) {
         *      // non-localized version
         *      Uri source = new Uri(imagePath);
         *
         *      ExifMetadata meta = new ExifMetadata(source);
         *
         *      Dictionary<string, object> metaInfo = new Dictionary<string,object>();
         *
         *      Type t = typeof(ExifMetadata);
         *      PropertyInfo[] pi = t.GetProperties();
         *
         *      for (int i = 0; i < pi.Length; i++) {
         *              object[] attr = pi[i].GetCustomAttributes(true);
         *
         *              for (int j = 0; j < attr.Length; j++) {
         *                      if (attr[j] is ExifDisplayAttribute) {
         *                              ExifDisplayAttribute exifAttri = (ExifDisplayAttribute)attr[j];
         *
         *                              //string displayName = exifAttri.DisplayName;
         *                              string displayName = Resources.LanguageContent.ResourceManager.GetString(exifAttri.DisplayName,
         *                                      Thread.CurrentThread.CurrentCulture);
         *                              object propertyValue = pi[i].GetValue(meta, null);
         *
         *                              metaInfo.Add(displayName, propertyValue);
         *                      }
         *              }
         *      }
         *
         *      return metaInfo;
         * }*/

        /*
         * private DataTable getExifMetaData(string imagePath) {
         *      DataTable dt = new DataTable();
         *      dt.Columns.Add(new DataColumn("Attribute", typeof(string)));
         *      dt.Columns.Add(new DataColumn("Value", typeof(string)));
         *
         *      Uri source = new Uri(imagePath);
         *
         *      ExifMetadata meta = new ExifMetadata(source);
         *
         *      Type t = typeof(ExifMetadata);
         *      PropertyInfo[] pi = t.GetProperties();
         *
         *      for (int i = 0; i < pi.Length; i++) {
         *              object[] attr = pi[i].GetCustomAttributes(true);
         *
         *              for (int j = 0; j < attr.Length; j++) {
         *                      if (attr[j] is ExifDisplayAttribute) {
         *                              ExifDisplayAttribute exifAttri = (ExifDisplayAttribute)attr[j];
         *
         *                              //string displayName = exifAttri.DisplayName;
         *                              string displayName = Resources.LanguageContent.ResourceManager.GetString(exifAttri.DisplayName,
         *                                      Thread.CurrentThread.CurrentCulture);
         *                              object propertyValue = pi[i].GetValue(meta, null);
         *
         *                              string localizedValue;
         *                              if (pi[i].PropertyType.IsEnum) {
         *                                      localizedValue = getValueDisplayName(propertyValue);
         *                              } else {
         *                                      localizedValue = propertyValue == null ? string.Empty : propertyValue.ToString();
         *                              }
         *
         *                              string valueFormat = exifAttri.ValueFormat;
         *                              if (!string.IsNullOrEmpty(valueFormat)) {
         *                                      // value format is specified, read from resource then
         *                                      valueFormat = Resources.LanguageContent.ResourceManager.GetString(valueFormat,
         *                                              Thread.CurrentThread.CurrentCulture);
         *
         *                                      if (!string.IsNullOrEmpty(valueFormat)) {
         *                                              // make sure the value format could be loaded from resource
         *                                              valueFormat = string.Format(valueFormat, localizedValue);
         *
         *                                              dt.Rows.Add(new object[] { displayName, valueFormat });
         *                                      } else {
         *                                              dt.Rows.Add(new object[] { displayName, localizedValue });
         *                                      }
         *                              } else {
         *                                      dt.Rows.Add(new object[] { displayName, localizedValue });
         *                              }
         *                      }
         *              }
         *      }
         *
         *      return dt;
         * }
         *
         * private string getValueDisplayName(object propertyValue) {
         *      if (propertyValue == null) {
         *              return string.Empty;
         *      } else {
         *              return Utilities.GetEnumItemDisplayValue(propertyValue);
         *      }
         * }*/

        private DataTable getExifMetaData(string imagePath)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("Attribute", typeof(string)));
            dt.Columns.Add(new DataColumn("Value", typeof(string)));

            Uri source = new Uri(imagePath);

            ExifMetadata meta = new ExifMetadata(source, true);

            List <ExifContainerItem> exifContainer = Utilities.GetExifContainer();

            foreach (ExifContainerItem item in exifContainer)
            {
                object propertyValue = item.Property.GetValue(meta, null);

                string localizedValue;
                if (propertyValue == null)
                {
                    localizedValue = string.Empty;
                }
                else
                {
                    if (item.Property.PropertyType.IsEnum)
                    {
                        // if this is assembly Enum, then get (localized) display name of the enum
                        localizedValue = Utilities.GetEnumItemDisplayValue(propertyValue);
                    }
                    else
                    {
                        // otherwise use the property value
                        localizedValue = propertyValue.ToString();
                    }
                }

                if (!string.IsNullOrEmpty(item.ValueFormat) && !string.IsNullOrEmpty(localizedValue))
                {
                    // value format is specified, read from resource then
                    string displayValue = string.Format(item.ValueFormat, localizedValue);

                    dt.Rows.Add(new object[] { item.DisplayLabel, displayValue });
                }
                else
                {
                    dt.Rows.Add(new object[] { item.DisplayLabel, localizedValue });
                }
            }

            return(dt);
        }
Пример #10
0
 public void Refresh()
 {
     if (this.source != null)
     {
         this.image        = BitmapFrame.Create(this.source);
         this.exifMetadata = new ExifMetadata(this.source);
         this.exists       = true;
     }
     else
     {
         this.image        = null;
         this.exifMetadata = new ExifMetadata();
         this.exists       = false;
     }
 }
Пример #11
0
        public DateTime GetDateTaken(string strPicture)
        {
            string strSQL = "";

            try
            {
                string strPic = strPicture;
                DatabaseUtility.RemoveInvalidChars(ref strPic);

                strSQL = String.Format("select * from tblPicture where strFile like '{0}'", strPic);
                using (SqlCommand cmd = _connection.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = strSQL;
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            DateTime dtDateTime = (DateTime)reader["strDateTaken"];
                            reader.Close();
                            return(dtDateTime);
                        }
                        reader.Close();
                    }
                }
                AddPicture(strPicture, -1);
                string strDateTime;
                using (ExifMetadata extractor = new ExifMetadata())
                {
                    ExifMetadata.Metadata metaData = extractor.GetExifMetadata(strPic);
                    strDateTime = DateTime.Parse(metaData.DatePictureTaken.DisplayValue).ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (strDateTime != string.Empty && strDateTime != "")
                {
                    DateTime dtDateTime = DateTime.ParseExact(strDateTime, "yyyy-MM-dd HH:mm:ss", new CultureInfo(""));
                    return(dtDateTime);
                }
                else
                {
                    return(DateTime.MinValue);
                }
            }
            catch (Exception ex)
            {
                Log.Error("MediaPortal.Picture.Database exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
            }
            return(DateTime.MinValue);
        }
Пример #12
0
        public int GetRotation(string strPicture)
        {
            // Continue only if it's a picture files
            if (!Util.Utils.IsPicture(strPicture))
            {
                return(-1);
            }

            string strSQL = "";

            try
            {
                string strPic = strPicture;
                int    iRotation;
                DatabaseUtility.RemoveInvalidChars(ref strPic);

                strSQL = String.Format("select * from tblPicture where strFile like '{0}'", strPic);
                using (SqlCommand cmd = _connection.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = strSQL;
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            iRotation = (int)reader["iRotation"];
                            reader.Close();
                            return(iRotation);
                        }
                        reader.Close();
                    }
                }

                ExifMetadata          extractor = new ExifMetadata();
                ExifMetadata.Metadata metaData  = extractor.GetExifMetadata(strPicture);
                iRotation = EXIFOrientationToRotation(Convert.ToInt32(metaData.Orientation.Hex));

                AddPicture(strPicture, iRotation);
                return(0);
            }
            catch (Exception ex)
            {
                Log.Error("MediaPortal.Picture.Database exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
            }
            return(0);
        }
Пример #13
0
        public void Test3()
        {
            var image = new ImageInfo {
                Format      = "tiff",
                PixelFormat = PixelFormat.Cmyk32,
                Width       = 1_000_000,
                Height      = 1_000_000,
                ColorSpace  = ColorSpace.CMYK,
                Exif        = new ExifMetadata {
                    Orientation = ExifOrientation.Rotate90
                }
            };

            var image2 = Helper.SerializeAndBack(image);

            Assert.Equal("tiff", image2.Format);
            Assert.Equal(1_000_000, image2.Width);
            Assert.Equal(1_000_000, image2.Height);
            Assert.Equal(ExifOrientation.Rotate90, image2.Exif.Orientation);
            Assert.Equal(PixelFormat.Cmyk32, image2.PixelFormat);
        }
        private string ConvertExifTagsToText(string input, List <ExifContainerItem> tagsFound)
        {
            ExifMetadata meta = new ExifMetadata(new Uri(this.ImageFileName), true);

            foreach (ExifContainerItem tagFound in tagsFound)
            {
                // replace actual value from Exif in watermark text
                string tag           = "[[" + tagFound.ExifTag + "]]";
                object propertyValue = tagFound.Property.GetValue(meta, null);
                string localizedValue;
                if (propertyValue == null)
                {
                    localizedValue = string.Empty;
                }
                else
                {
                    if (tagFound.Property.PropertyType.IsEnum && tagFound.EnumValueTranslation != null)
                    {
                        localizedValue = propertyValue.ToString();

                        foreach (KeyValuePair <string, string> enumItem in tagFound.EnumValueTranslation)
                        {
                            if (localizedValue == enumItem.Key)
                            {
                                localizedValue = enumItem.Value;
                                break;
                            }
                        }
                    }
                    else if (tagFound.Property.PropertyType == typeof(DateTime?))
                    {
#if DEBUG
                        Debug.WriteLine("Current Thread "
                                        + System.Threading.Thread.CurrentThread.ManagedThreadId + " Culture "
                                        + System.Threading.Thread.CurrentThread.CurrentCulture.ToString()
                                        + " in ApplyWatermarkText.");
#endif
                        // date time value, use format string defined in preference window to overwrite
                        DateTime?d = (DateTime?)propertyValue;
                        if (d.HasValue)
                        {
                            localizedValue = d.Value.ToString(this.dateTimeStringFormat);
                        }
                        else
                        {
                            localizedValue = string.Empty;
                        }
                    }
                    else
                    {
                        localizedValue = propertyValue.ToString();
                    }

                    if (!string.IsNullOrEmpty(tagFound.ValueFormat))
                    {
                        localizedValue = string.Format(tagFound.ValueFormat, localizedValue);
                    }
                }
                input = input.Replace(tag, localizedValue);
            }
            return(input);
        }
        //ExEnd:ApplyLicense
        public static string CleanFile(string filePath)
        {

            try
            {
                try
                {
                    //Apply license...
                    ApplyLicense();

                }
                catch (Exception exp)
                {
                    MessageBox.Show("In Licence: " + exp.Message);
                }
                try
                {
                    //Recognize format of file...
                    FormatBase format = FormatFactory.RecognizeFormat(filePath);

                    if (format.Type.ToString().ToLower() == "doc" || format.Type.ToString().ToLower() == "docx")
                    {
                        // initialize DocFormat...
                        DocFormat docFormat = format as DocFormat;
                        if (docFormat != null)
                        {
                            // get document properties...
                            DocMetadata properties = new DocMetadata();
                            properties = docFormat.DocumentProperties;

                            //Remove custom properties...
                            foreach (KeyValuePair<string, PropertyValue> keyValuePair in properties)
                            {
                                if (!properties.IsBuiltIn(keyValuePair.Key))
                                {
                                    properties.Remove(keyValuePair.Key);
                                }
                            }

                            //Reset built-in properties...
                            properties.Author = "";
                            properties.Category = "";
                            properties.Comments = "";
                            properties.Company = "";
                            properties.ContentStatus = "";
                            properties.HyperlinkBase = "";
                            properties.Keywords = "";
                            properties.Manager = "";
                            properties.Title = "";

                            //Update metadata if file...
                            MetadataUtility.UpdateMetadata(filePath, properties);

                        }
                        return "1";
                    }
                    else if (format.Type.ToString().ToLower() == "xls" || format.Type.ToString().ToLower() == "xlsx")
                    {
                        //Initialize XlsFormat...
                        XlsFormat xlsFormat = format as XlsFormat;
                        if (xlsFormat != null)
                        { 
                            //Get document properties...
                            XlsMetadata properties = xlsFormat.DocumentProperties;
                            
                            //Remove custom properties...
                            foreach (KeyValuePair<string, PropertyValue> keyValuePair in properties)
                            {
                                if (!properties.IsBuiltIn(keyValuePair.Key))
                                {
                                    properties.Remove(keyValuePair.Key);
                                }
                            }

                            //Reset built-in properties...
                            properties.Author = "";
                            properties.Category = "";
                            properties.Comments = "";
                            properties.Company = "";
                            properties.HyperlinkBase = "";
                            properties.Keywords = "";
                            properties.Manager = "";
                            properties.Title = "";
                            properties.Subject = "";

                            //Update metadata in files...
                            MetadataUtility.UpdateMetadata(filePath, properties);
                        }
                        return "1";
                    }
                    else if (format.Type.ToString().ToLower() == "ppt" || format.Type.ToString().ToLower() == "pptx")
                    {
                        //Initialize PptFormat...
                        PptFormat pptFormat = format as PptFormat;
                        if (pptFormat != null)
                        {
                            //Get document properties...
                            PptMetadata properties = pptFormat.DocumentProperties;

                            //Remove custom properties
                            foreach (KeyValuePair<string, PropertyValue> keyValuePair in properties)
                            {
                                if (!properties.IsBuiltIn(keyValuePair.Key))
                                {
                                    properties.Remove(keyValuePair.Key);
                                }
                            }

                            //Reset built-in properties...
                            properties.Author = "";
                            properties.Category = "";
                            properties.Comments = "";
                            properties.Company = "";
                            properties.Keywords = "";
                            properties.Manager = "";
                            properties.Title = "";
                            properties.Subject = "";

                            //Update metadata of file...
                            MetadataUtility.UpdateMetadata(filePath, properties); 
                        }
                        return "1";
                    }
                    else if (format.Type.ToString().ToLower() == "pdf")
                    {
                        // initialize PdfFormat...
                        PdfFormat pdfFormat = format as PdfFormat;
                        if (pdfFormat != null)
                        {
                            // get document properties...
                            PdfMetadata properties = pdfFormat.DocumentProperties; 

                            // Remove custom properties...
                            foreach (KeyValuePair<string, PropertyValue> keyValuePair in properties)
                            {
                                if (!properties.IsBuiltIn(keyValuePair.Key))
                                {
                                    properties.Remove(keyValuePair.Key);
                                }
                            }

                            //Reset built-in properties...
                            properties.Author = "";
                            properties.CreatedDate = DateTime.MinValue;
                            properties.Keywords = "";
                            properties.ModifiedDate = DateTime.MinValue;
                            properties.Subject = "";
                            properties.TrappedFlag = false;
                            properties.Title = "";

                            //Update metadata of file... 
                            MetadataUtility.UpdateMetadata(filePath, properties);
                        }
                        return "1";
                    }
                    else if (format.Type.ToString().ToLower() == "jpeg" || format.Type.ToString().ToLower() == "jpg")
                    {
                        //Get EXIF data if exists 
                        ExifMetadata exifMetadata = (ExifMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.EXIF);
                        
                        //Get XMP data if exists
                        XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP);
                        if (exifMetadata != null)
                        {
                            //Remove exif info... 
                            ExifInfo exifInfo = exifMetadata.Data;

                            if (exifInfo.GPSData != null)
                            {
                                // set altitude, latitude and longitude to null values
                                exifInfo.GPSData.Altitude = null;
                                exifInfo.GPSData.Latitude = null;
                                exifInfo.GPSData.LatitudeRef = null;
                                exifInfo.GPSData.Longitude = null;
                                exifInfo.GPSData.LongitudeRef = null;
                            }
                            exifInfo.BodySerialNumber = "";
                            exifInfo.CameraOwnerName = "";
                            exifInfo.CFAPattern = new byte[] { 0 };
                        }
                        else
                        {
                            exifMetadata = new ExifMetadata();
                        }
                        try
                        {
                            //Remove XMP data...
                            XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket;
                            if (xmpPacket != null)
                            {
                                if (xmpPacket.ContainsPackage(Namespaces.DublinCore))
                                {
                                    // if not - add DublinCore schema
                                    xmpPacket.AddPackage(new DublinCorePackage());
                                    DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore);
                                    dublinCorePackage.Clear();
                                    xmpMetadata.XmpPacket = xmpPacket;
                                }
                            }
                        }
                        catch { }

                        //Update Exif info...
                        try
                        {
                            MetadataUtility.UpdateMetadata(filePath, exifMetadata);
                        }
                        catch { }

                        //Update XMP data...
                        try
                        {
                            MetadataUtility.UpdateMetadata(filePath, xmpMetadata);
                        }
                        catch { }

                        //Remove custom metadata if any...
                        MetadataUtility.CleanMetadata(filePath);
                        
                        return "1";
                    }
                    else if (format.Type.ToString().ToLower() == "png")
                    {
                        //Get XMP data...
                        XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP);
                        try
                        {
                            //Remove XMP metadata...
                            XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket;
                            if (xmpPacket != null)
                            {
                                if (xmpPacket.ContainsPackage(Namespaces.DublinCore))
                                {
                                    // if not - add DublinCore schema
                                    xmpPacket.AddPackage(new DublinCorePackage());
                                    DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore);
                                    dublinCorePackage.Clear();
                                    xmpMetadata.XmpPacket = xmpPacket;

                                    //Update XMP metadata in file...
                                    MetadataUtility.UpdateMetadata(filePath, xmpMetadata);

                                    //Clean custom metadata if any...
                                    MetadataUtility.CleanMetadata(filePath);
                                }
                            }
                        }
                        catch { }

                        return "1";
                    }
                    else if (format.Type.ToString().ToLower() == "gif")
                    {
                        //Initialie GifFormat...
                        GifFormat gifFormat = new GifFormat(filePath);

                        //Check if Xmp supported...
                        if (gifFormat.IsSupportedXmp)
                        {
                            //Get XMP data...
                            XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP);
                            try
                            {
                                XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket;
                                if (xmpPacket != null)
                                {
                                    if (xmpPacket.ContainsPackage(Namespaces.DublinCore))
                                    {
                                        // if not - add DublinCore schema
                                        xmpPacket.AddPackage(new DublinCorePackage());
                                        DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore);
                                        dublinCorePackage.Clear();
                                        xmpMetadata.XmpPacket = xmpPacket;

                                        //Update Xmp data in file...
                                        MetadataUtility.UpdateMetadata(filePath, xmpMetadata);
                                        //Clean custom metadata if any...
                                        MetadataUtility.CleanMetadata(filePath);
                                    }
                                }
                            }
                            catch { }
                        }
                        return "1";
                    }
                    else
                    {
                        return "Format not supported.";
                    }
                }
                catch( Exception exp)
                {
                    MessageBox.Show("Exception: " + exp.Message);
                    return exp.Message;
                }

            }
            catch (Exception exp)
            {
                return exp.Message;
            }

        }
Пример #16
0
        public void GetDirectoryOfType_DirectoriesIsNull()
        {
            var metadata = new ExifMetadata(null, null);

            Assert.IsNull(metadata.GetDirectoryOfType <string>());
        }
Пример #17
0
        public int AddPicture(string strPicture, int iRotation)
        {
            // Continue only if it's a picture files
            if (!Util.Utils.IsPicture(strPicture))
            {
                return(-1);
            }

            if (strPicture == null)
            {
                return(-1);
            }
            if (strPicture.Length == 0)
            {
                return(-1);
            }
            lock (typeof(PictureDatabase))
            {
                string strSQL = "";
                try
                {
                    string strPic = strPicture;
                    DatabaseUtility.RemoveInvalidChars(ref strPic);

                    strSQL = String.Format("select * from tblPicture where strFile like '{0}'", strPic);
                    using (SqlCommand cmd = _connection.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = strSQL;
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                int id = (int)reader["idPicture"];
                                reader.Close();
                                return(id);
                            }
                            reader.Close();
                        }
                    }

                    //Changed mbuzina
                    DateTime dateTaken = DateTime.Now;
                    using (ExifMetadata extractor = new ExifMetadata())
                    {
                        ExifMetadata.Metadata metaData = extractor.GetExifMetadata(strPic);
                        try
                        {
                            DateTimeFormatInfo dateTimeFormat = new DateTimeFormatInfo();
                            dateTimeFormat.ShortDatePattern = "yyyy:MM:dd HH:mm:ss";

                            dateTaken = DateTime.ParseExact(metaData.DatePictureTaken.DisplayValue, "d", dateTimeFormat);
                        }
                        catch (Exception) {}
                        // Smirnoff: Query the orientation information
                        //						if(iRotation == -1)
                        iRotation = EXIFOrientationToRotation(Convert.ToInt32(metaData.Orientation.Hex));
                    }
                    strSQL = String.Format("insert into tblPicture (strFile, iRotation, strDateTaken) values('{0}',{1},'{2}')",
                                           strPic, iRotation, dateTaken);
                    return(SqlServerUtility.InsertRecord(_connection, strSQL));
                }
                catch (Exception ex)
                {
                    Log.Error("MediaPortal.Picture.Database exception err:{0} stack:{1}", ex.Message, ex.StackTrace);
                }
                return(-1);
            }
        }
Пример #18
0
        private void ProcessImage(object threadIndex)
        {
            int index = (int)threadIndex;

            Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " is created to process indexed item [" + index + "] at " + DateTime.Now + ".");
            Trace.WriteLine("Current Thread " + Thread.CurrentThread.ManagedThreadId + " Culture " + Thread.CurrentThread.CurrentCulture.ToString() + " during processing.");

            string imagePath  = string.Empty;
            uint   imageIndex = 0;

            lock (syncRoot) {
                if (jobQueue.Count > 0)
                {
                    JobItem item = jobQueue.Dequeue();

                    imagePath  = item.FileName;
                    imageIndex = item.Index;
                    Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " is handling " + imagePath);
                }
                else
                {
                    // nothing more to process, signal
#if DEBUG
                    Debug.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " is set because no more image to process at " + DateTime.Now + ".");
#endif
                    events[index].Set();
                    return;
                }
            }

            if (stopFlag)
            {
                // stop requested, signal
#if DEBUG
                Debug.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " is set because stop requested.");
#endif
                events[index].Set();
                return;
            }
            else
            {
                ExifMetadata exif = null;

                Image normalImage = null;
                Image thumbImage  = null;
                try {
                    if (ps.KeepExif)
                    {
                        // keep exif information from original file
                        exif = new ExifMetadata(new Uri(imagePath), true);
                        Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " obtained EXIF for " + imagePath + " at " + DateTime.Now + ".");
                    }

                    // this will lock image until entire application quits: normalImage = Image.FromFile(imagePath);
                    // following code won't lock image.
                    using (Stream stream = File.OpenRead(imagePath)) {
                        normalImage = Image.FromStream(stream);
                        Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " opened " + imagePath + " at " + DateTime.Now + ".");
                    }

                    ImageFormat format = getImageFormat(imagePath);

                    IProcess process;

                    // thumbnail operation
                    if (ps.ThumbnailSetting.GenerateThumbnail && ps.ThumbnailSetting.ThumbnailSize > 0)
                    {
                        process    = container.Resolve <IProcess>("ThumbImage");
                        thumbImage = process.ProcessImage(normalImage, this.ps);
                        Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " processed thumbnail for " + imagePath + " at " + DateTime.Now + ".");
                    }

                    // shrink image operation
                    if (ps.ShrinkImage && ps.ShrinkPixelTo > 0)
                    {
                        process     = container.Resolve <IProcess>("ShrinkImage");
                        normalImage = process.ProcessImage(normalImage, this.ps);
                        Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " shrinked " + imagePath + " at " + DateTime.Now + ".");
                    }

                    // image process effect
                    if (ps.ProcessType != ImageProcessType.None)
                    {
                        switch (ps.ProcessType)
                        {
                        case ImageProcessType.GrayScale:
                            process     = container.Resolve <IProcess>("GrayscaleEffect");
                            normalImage = process.ProcessImage(normalImage, null);
                            Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " applied GrayscaleEffect for " + imagePath + " at " + DateTime.Now + ".");
                            break;

                        case ImageProcessType.NagativeImage:
                            process     = container.Resolve <IProcess>("NegativeEffect");
                            normalImage = process.ProcessImage(normalImage, null);
                            Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " applied NegativeEffect for " + imagePath + " at " + DateTime.Now + ".");
                            break;

                        case ImageProcessType.OilPaint:
                            process     = container.Resolve <IProcess>("OilPaintEffect");
                            normalImage = process.ProcessImage(normalImage, null);
                            Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " applied OilPaintEffect for " + imagePath + " at " + DateTime.Now + ".");
                            break;

                        case ImageProcessType.PencilSketch:
                            process     = container.Resolve <IProcess>("PencilSketchEffect");
                            normalImage = process.ProcessImage(normalImage, null);
                            Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " applied PencilSketchEffect for " + imagePath + " at " + DateTime.Now + ".");
                            break;

                        case ImageProcessType.Relief:
                            process     = container.Resolve <IProcess>("ReliefEffect");
                            normalImage = process.ProcessImage(normalImage, null);
                            Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " applied ReliefEffect for " + imagePath + " at " + DateTime.Now + ".");
                            break;

                        default:
                            break;
                        }
                    }

                    if (ps.WatermarkCollection != null && ps.WatermarkCollection.Count > 0)
                    {
                        IUnityContainer watermarkContainer;
                        watermarkContainer = container.CreateChildContainer();
                        watermarkContainer.RegisterInstance <List <ExifContainerItem> >(exifContainer)
                        .RegisterInstance <string>(dateTimeStringFormat);

                        for (int watermarkIndex = 0; watermarkIndex < ps.WatermarkCollection.Count; watermarkIndex++)
                        {
                            watermarkContainer.RegisterInstance <int>(watermarkIndex);

                            if (ps.WatermarkCollection[watermarkIndex] is WatermarkText)
                            {
                                // text watermark operation
                                WatermarkText wt = ps.WatermarkCollection[watermarkIndex] as WatermarkText;
                                if (!string.IsNullOrEmpty(wt.Text) && wt.WatermarkTextColor.A > 0)
                                {
#if DEBUG
                                    Debug.WriteLine("Current Thread "
                                                    + Thread.CurrentThread.ManagedThreadId + " Culture "
                                                    + Thread.CurrentThread.CurrentCulture.ToString()
                                                    + " before ApplyWatermarkText.");

                                    Debug.WriteLine("Current Thread: "
                                                    + Thread.CurrentThread.ManagedThreadId + ";"
                                                    + " Image File Name: " + imagePath + ","
                                                    + " Watermark Text index: " + watermarkIndex
                                                    + " before.");
#endif
                                    //process = container.Resolve<IProcess>("WatermarkText");
                                    process = watermarkContainer.Resolve <IProcess>("WatermarkText");
                                    process.ImageFileName = imagePath;
                                    normalImage           = process.ProcessImage(normalImage, this.ps);
                                }
                            }
                            else if (ps.WatermarkCollection[watermarkIndex] is WatermarkImage)
                            {
                                // image watermark operation
                                WatermarkImage wi = ps.WatermarkCollection[watermarkIndex] as WatermarkImage;
                                if (!string.IsNullOrEmpty(wi.WatermarkImageFile) &&
                                    File.Exists(wi.WatermarkImageFile) &&
                                    wi.WatermarkImageOpacity > 0)
                                {
#if DEBUG
                                    System.Diagnostics.Debug.WriteLine("Current Thread: "
                                                                       + System.Threading.Thread.CurrentThread.ManagedThreadId + ";"
                                                                       + " Image File Name: " + imagePath + ","
                                                                       + " Watermark Image index: " + watermarkIndex
                                                                       + " before.");
#endif
                                    process = watermarkContainer.Resolve <IProcess>("WatermarkImage");
                                    process.ImageFileName = imagePath;
                                    normalImage           = process.ProcessImage(normalImage, this.ps);
                                }
                            }
                        }

                        Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " applied watermark(s) for " + imagePath + " at " + DateTime.Now + ".");
                    }

                    // border operation
                    if (ps.BorderSetting.BorderWidth > 0)
                    {
                        process     = container.Resolve <IProcess>("AddBorder");
                        normalImage = process.ProcessImage(normalImage, this.ps);
                        Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " added border for " + imagePath + " at " + DateTime.Now + ".");
                    }

                    // drop shadow operation
                    if (ps.DropShadowSetting.ShadowDepth > 0)
                    {
                        process     = container.Resolve <IProcess>("DropShadow");
                        normalImage = process.ProcessImage(normalImage, this.ps);
                        Trace.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " added dropshadow for " + imagePath + " at " + DateTime.Now + ".");
                    }

                    IFilenameProvider fileNameProvider;

                    if (ps.RenamingSetting.EnableBatchRename)
                    {
                        fileNameProvider = container.Resolve <IFilenameProvider>("BatchRenamedFileName");
                    }
                    else
                    {
                        fileNameProvider = container.Resolve <IFilenameProvider>("NormalFileName");
                    }
                    fileNameProvider.PS             = ps;
                    fileNameProvider.ImageIndex     = imageIndex;
                    fileNameProvider.SourceFileName = imagePath;

                    ISaveImage imageSaver;
                    if (format == ImageFormat.Jpeg)
                    {
                        imageSaver      = container.Resolve <ISaveImage>("SaveCompressedJpgImage");
                        imageSaver.Exif = exif;
                    }
                    else
                    {
                        imageSaver = container.Resolve <ISaveImage>("SaveNormalImage");
                    }
                    imageSaver.SaveImageToDisk(normalImage, format, fileNameProvider);

                    if (thumbImage != null)
                    {
                        // TODO think about applying thumbImage file name to batch renamed original file
                        fileNameProvider                = container.Resolve <IFilenameProvider>("ThumbFileName");
                        fileNameProvider.PS             = ps;
                        fileNameProvider.ImageIndex     = imageIndex;
                        fileNameProvider.SourceFileName = imagePath;
                        //saveImage(imagePath, thumbImage, format, fileNameProvider, imageSaver, imageIndex);
                        imageSaver.SaveImageToDisk(thumbImage, format, fileNameProvider);
                    }
                } catch (Exception ex) {
                    Trace.TraceError(ex.ToString());
                } finally {
                    if (normalImage != null)
                    {
                        // if there is an source image in queue which does not exist any more, this could be null.
                        normalImage.Dispose();
                        normalImage = null;
                    }

                    if (thumbImage != null)
                    {
                        thumbImage.Dispose();
                        thumbImage = null;
                    }

                    ImageProcessedEventArgs args = new ImageProcessedEventArgs(imagePath);
                    OnImageProcessed(args);
                }

                // recursively call itself to go back to check if there are more files waiting to be processed.
                ProcessImage(threadIndex);
            }
        }
Пример #19
0
        /// <summary>
        /// Returns latest added Pictures db.
        /// </summary>
        /// <param name="type">Type of data to fetch</param>
        /// <returns>Resultset of matching data</returns>
        private LatestsCollection GetLatestPictures()
        {
            latestPictures      = new LatestsCollection();
            latestPicturesFiles = new Hashtable();

            if (!InitDB())
            {
                return(latestPictures);
            }

            int x = 0;

            try
            {
                CurrentFacade.HasNew = false;

                string          sqlQuery  = "SELECT strFile, strDateTaken FROM picture ORDER BY strDateTaken DESC LIMIT " + Utils.FacadeMaxNum + ";";
                SQLiteResultSet resultSet = PicturesDB.Execute(sqlQuery);
                CloseDB();

                if (resultSet != null)
                {
                    if (resultSet.Rows.Count > 0)
                    {
                        int i0 = 1;
                        for (int i = 0; i < resultSet.Rows.Count; i++)
                        {
                            string filename = resultSet.GetField(i, 0);
                            if (string.IsNullOrEmpty(filename))
                            {
                                continue;
                            }

                            // string thumb = String.Format(@"{0}\{1}L.jpg", Thumbs.Pictures, MediaPortal.Util.Utils.EncryptLine(filename));
                            string thumb = MediaPortal.Util.Utils.GetPicturesLargeThumbPathname(filename);
                            if (!File.Exists(thumb))
                            {
                                // thumb = String.Format(@"{0}\{1}.jpg", Thumbs.Pictures, MediaPortal.Util.Utils.EncryptLine(filename));
                                thumb = MediaPortal.Util.Utils.GetPicturesThumbPathname(filename);
                                if (!File.Exists(thumb))
                                {
                                    // thumb = "DefaultPictureBig.png";
                                    thumb = filename;
                                }
                            }
                            if (!File.Exists(thumb))
                            {
                                continue;
                            }

                            string dateAdded = resultSet.GetField(i, 1);
                            bool   isnew     = false;
                            try
                            {
                                DateTime dTmp = DateTime.Parse(dateAdded);
                                dateAdded = String.Format("{0:" + Utils.DateFormat + "}", dTmp);

                                isnew = (dTmp > Utils.NewDateTime);
                                if (isnew)
                                {
                                    CurrentFacade.HasNew = true;
                                }
                            }
                            catch {   }

                            string title = Path.GetFileNameWithoutExtension(Utils.GetFilenameNoPath(filename)).ToUpperInvariant();

                            string exif        = string.Empty;
                            string exifoutline = string.Empty;
                            if (File.Exists(filename))
                            {
                                using (ExifMetadata extractor = new ExifMetadata())
                                {
                                    ExifMetadata.Metadata metaData = extractor.GetExifMetadata(filename);

                                    exif = exif + (!string.IsNullOrEmpty(metaData.CameraModel.DisplayValue) ? metaData.CameraModel.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.DatePictureTaken.DisplayValue) ? metaData.DatePictureTaken.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.EquipmentMake.DisplayValue) ? metaData.EquipmentMake.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.ExposureCompensation.DisplayValue) ? metaData.ExposureCompensation.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.ExposureTime.DisplayValue) ?metaData.ExposureTime.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.Flash.DisplayValue) ? metaData.Flash.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.Fstop.DisplayValue) ? metaData.Fstop.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.ImageDimensions.DisplayValue) ? metaData.ImageDimensions.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.MeteringMode.DisplayValue) ? metaData.MeteringMode.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.Resolution.DisplayValue) ? metaData.Resolution.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.ShutterSpeed.DisplayValue) ? metaData.ShutterSpeed.DisplayValue + System.Environment.NewLine : string.Empty);
                                    exif = exif + (!string.IsNullOrEmpty(metaData.ViewerComments.DisplayValue) ? metaData.ViewerComments.DisplayValue + System.Environment.NewLine : string.Empty);

                                    exifoutline = exifoutline + (!string.IsNullOrEmpty(metaData.EquipmentMake.DisplayValue) ? metaData.EquipmentMake.DisplayValue + " " : string.Empty);
                                    exifoutline = exifoutline + (!string.IsNullOrEmpty(metaData.CameraModel.DisplayValue) ? metaData.CameraModel.DisplayValue + " " : string.Empty);
                                    exifoutline = exifoutline + (!string.IsNullOrEmpty(metaData.ViewerComments.DisplayValue) ? metaData.ViewerComments.DisplayValue + " " : string.Empty);
                                }
                            }

                            latestPictures.Add(new Latest(dateAdded, thumb, filename, title, exifoutline,
                                                          null, null, null, null, null, null,
                                                          null, null, null, null, null, null, null,
                                                          exif, null, isnew));
                            latestPicturesFiles.Add(i0, filename);
                            Utils.ThreadToSleep();

                            x++;
                            i0++;
                            if (x == Utils.FacadeMaxNum)
                            {
                                break;
                            }
                        }
                    }
                }
                resultSet = null;
            }
            catch (Exception ex)
            {
                logger.Error("GetLatestPictures: " + ex.ToString());
            }
            return(latestPictures);
        }
        //ExEnd:ApplyLicense
        public static string CleanFile(string filePath)
        {
            try
            {
                try
                {
                    //Apply license...
                    ApplyLicense();
                }
                catch (Exception exp)
                {
                    MessageBox.Show("In Licence: " + exp.Message);
                }
                try
                {
                    //Recognize format of file...
                    FormatBase format = FormatFactory.RecognizeFormat(filePath);

                    if (format.Type.ToString().ToLower() == "doc" || format.Type.ToString().ToLower() == "docx")
                    {
                        // initialize DocFormat...
                        DocFormat docFormat = format as DocFormat;
                        if (docFormat != null)
                        {
                            // get document properties...
                            DocMetadata properties = new DocMetadata();
                            properties = docFormat.DocumentProperties;

                            //Remove custom properties...
                            foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties)
                            {
                                if (!properties.IsBuiltIn(keyValuePair.Key))
                                {
                                    properties.Remove(keyValuePair.Key);
                                }
                            }

                            //Reset built-in properties...
                            properties.Author        = "";
                            properties.Category      = "";
                            properties.Comments      = "";
                            properties.Company       = "";
                            properties.ContentStatus = "";
                            properties.HyperlinkBase = "";
                            properties.Keywords      = "";
                            properties.Manager       = "";
                            properties.Title         = "";

                            //Update metadata if file...
                            MetadataUtility.UpdateMetadata(filePath, properties);
                        }
                        return("1");
                    }
                    else if (format.Type.ToString().ToLower() == "xls" || format.Type.ToString().ToLower() == "xlsx")
                    {
                        //Initialize XlsFormat...
                        XlsFormat xlsFormat = format as XlsFormat;
                        if (xlsFormat != null)
                        {
                            //Get document properties...
                            XlsMetadata properties = xlsFormat.DocumentProperties;

                            //Remove custom properties...
                            foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties)
                            {
                                if (!properties.IsBuiltIn(keyValuePair.Key))
                                {
                                    properties.Remove(keyValuePair.Key);
                                }
                            }

                            //Reset built-in properties...
                            properties.Author        = "";
                            properties.Category      = "";
                            properties.Comments      = "";
                            properties.Company       = "";
                            properties.HyperlinkBase = "";
                            properties.Keywords      = "";
                            properties.Manager       = "";
                            properties.Title         = "";
                            properties.Subject       = "";

                            //Update metadata in files...
                            MetadataUtility.UpdateMetadata(filePath, properties);
                        }
                        return("1");
                    }
                    else if (format.Type.ToString().ToLower() == "ppt" || format.Type.ToString().ToLower() == "pptx")
                    {
                        //Initialize PptFormat...
                        PptFormat pptFormat = format as PptFormat;
                        if (pptFormat != null)
                        {
                            //Get document properties...
                            PptMetadata properties = pptFormat.DocumentProperties;

                            //Remove custom properties
                            foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties)
                            {
                                if (!properties.IsBuiltIn(keyValuePair.Key))
                                {
                                    properties.Remove(keyValuePair.Key);
                                }
                            }

                            //Reset built-in properties...
                            properties.Author   = "";
                            properties.Category = "";
                            properties.Comments = "";
                            properties.Company  = "";
                            properties.Keywords = "";
                            properties.Manager  = "";
                            properties.Title    = "";
                            properties.Subject  = "";

                            //Update metadata of file...
                            MetadataUtility.UpdateMetadata(filePath, properties);
                        }
                        return("1");
                    }
                    else if (format.Type.ToString().ToLower() == "pdf")
                    {
                        // initialize PdfFormat...
                        PdfFormat pdfFormat = format as PdfFormat;
                        if (pdfFormat != null)
                        {
                            // get document properties...
                            PdfMetadata properties = pdfFormat.DocumentProperties;

                            // Remove custom properties...
                            foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties)
                            {
                                if (!properties.IsBuiltIn(keyValuePair.Key))
                                {
                                    properties.Remove(keyValuePair.Key);
                                }
                            }

                            //Reset built-in properties...
                            properties.Author       = "";
                            properties.CreatedDate  = DateTime.MinValue;
                            properties.Keywords     = "";
                            properties.ModifiedDate = DateTime.MinValue;
                            properties.Subject      = "";
                            properties.TrappedFlag  = false;
                            properties.Title        = "";

                            //Update metadata of file...
                            MetadataUtility.UpdateMetadata(filePath, properties);
                        }
                        return("1");
                    }
                    else if (format.Type.ToString().ToLower() == "jpeg" || format.Type.ToString().ToLower() == "jpg")
                    {
                        //Get EXIF data if exists
                        ExifMetadata exifMetadata = (ExifMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.EXIF);

                        //Get XMP data if exists
                        XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP);
                        if (exifMetadata != null)
                        {
                            //Remove exif info...
                            ExifInfo exifInfo = exifMetadata.Data;

                            if (exifInfo.GPSData != null)
                            {
                                // set altitude, latitude and longitude to null values
                                exifInfo.GPSData.Altitude     = null;
                                exifInfo.GPSData.Latitude     = null;
                                exifInfo.GPSData.LatitudeRef  = null;
                                exifInfo.GPSData.Longitude    = null;
                                exifInfo.GPSData.LongitudeRef = null;
                            }
                            exifInfo.BodySerialNumber = "";
                            exifInfo.CameraOwnerName  = "";
                            exifInfo.CFAPattern       = new byte[] { 0 };
                        }
                        else
                        {
                            exifMetadata = new ExifMetadata();
                        }
                        try
                        {
                            //Remove XMP data...
                            XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket;
                            if (xmpPacket != null)
                            {
                                if (xmpPacket.ContainsPackage(Namespaces.DublinCore))
                                {
                                    // if not - add DublinCore schema
                                    xmpPacket.AddPackage(new DublinCorePackage());
                                    DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore);
                                    dublinCorePackage.Clear();
                                    xmpMetadata.XmpPacket = xmpPacket;
                                }
                            }
                        }
                        catch { }

                        //Update Exif info...
                        try
                        {
                            MetadataUtility.UpdateMetadata(filePath, exifMetadata);
                        }
                        catch { }

                        //Update XMP data...
                        try
                        {
                            MetadataUtility.UpdateMetadata(filePath, xmpMetadata);
                        }
                        catch { }

                        //Remove custom metadata if any...
                        MetadataUtility.CleanMetadata(filePath);

                        return("1");
                    }
                    else if (format.Type.ToString().ToLower() == "png")
                    {
                        //Get XMP data...
                        XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP);
                        try
                        {
                            //Remove XMP metadata...
                            XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket;
                            if (xmpPacket != null)
                            {
                                if (xmpPacket.ContainsPackage(Namespaces.DublinCore))
                                {
                                    // if not - add DublinCore schema
                                    xmpPacket.AddPackage(new DublinCorePackage());
                                    DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore);
                                    dublinCorePackage.Clear();
                                    xmpMetadata.XmpPacket = xmpPacket;

                                    //Update XMP metadata in file...
                                    MetadataUtility.UpdateMetadata(filePath, xmpMetadata);

                                    //Clean custom metadata if any...
                                    MetadataUtility.CleanMetadata(filePath);
                                }
                            }
                        }
                        catch { }

                        return("1");
                    }
                    else if (format.Type.ToString().ToLower() == "gif")
                    {
                        //Initialie GifFormat...
                        GifFormat gifFormat = new GifFormat(filePath);

                        //Check if Xmp supported...
                        if (gifFormat.IsSupportedXmp)
                        {
                            //Get XMP data...
                            XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP);
                            try
                            {
                                XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket;
                                if (xmpPacket != null)
                                {
                                    if (xmpPacket.ContainsPackage(Namespaces.DublinCore))
                                    {
                                        // if not - add DublinCore schema
                                        xmpPacket.AddPackage(new DublinCorePackage());
                                        DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore);
                                        dublinCorePackage.Clear();
                                        xmpMetadata.XmpPacket = xmpPacket;

                                        //Update Xmp data in file...
                                        MetadataUtility.UpdateMetadata(filePath, xmpMetadata);
                                        //Clean custom metadata if any...
                                        MetadataUtility.CleanMetadata(filePath);
                                    }
                                }
                            }
                            catch { }
                        }
                        return("1");
                    }
                    else
                    {
                        return("Format not supported.");
                    }
                }
                catch (Exception exp)
                {
                    MessageBox.Show("Exception: " + exp.Message);
                    return(exp.Message);
                }
            }
            catch (Exception exp)
            {
                return(exp.Message);
            }
        }
Пример #21
0
        /// <summary>
        /// Returns latest added Pictures db.
        /// </summary>
        /// <param name="type">Type of data to fetch</param>
        /// <returns>Resultset of matching data</returns>
        private LatestsCollection GetLatestPictures()
        {
            latestPictures      = new LatestsCollection();
            latestPicturesFiles = new Hashtable();

            if (!PictureDatabase.DbHealth)
            {
                return(latestPictures);
            }

            int x = 0;

            try
            {
                CurrentFacade.HasNew = false;

                string sqlQuery = "SELECT strFile, strDateTaken FROM picture" +
                                  (PictureDatabase.FilterPrivate ? " WHERE idPicture NOT IN (SELECT DISTINCT idPicture FROM picturekeywords WHERE strKeyword = 'Private')" : string.Empty) +
                                  " ORDER BY strDateTaken DESC LIMIT " + Utils.FacadeMaxNum + ";";
                List <PictureData> pictures = PictureDatabase.GetPicturesByFilter(sqlQuery, "pictures");

                if (pictures != null)
                {
                    if (pictures.Count > 0)
                    {
                        int i0 = 1;
                        for (int i = 0; i < pictures.Count; i++)
                        {
                            string filename = pictures[i].FileName;
                            if (string.IsNullOrEmpty(filename))
                            {
                                continue;
                            }

                            // string thumb = String.Format(@"{0}\{1}L.jpg", Thumbs.Pictures, MediaPortal.Util.Utils.EncryptLine(filename));
                            string thumb = MediaPortal.Util.Utils.GetPicturesLargeThumbPathname(filename);
                            if (!File.Exists(thumb))
                            {
                                // thumb = String.Format(@"{0}\{1}.jpg", Thumbs.Pictures, MediaPortal.Util.Utils.EncryptLine(filename));
                                thumb = MediaPortal.Util.Utils.GetPicturesThumbPathname(filename);
                                if (!File.Exists(thumb))
                                {
                                    // thumb = "DefaultPictureBig.png";
                                    thumb = filename;
                                }
                            }
                            if (!File.Exists(thumb))
                            {
                                continue;
                            }

                            bool isnew = false;
                            isnew = (pictures[i].DateTaken > Utils.NewDateTime);
                            if (isnew)
                            {
                                CurrentFacade.HasNew = true;
                            }

                            string title = Path.GetFileNameWithoutExtension(Utils.GetFilenameNoPath(filename)).ToUpperInvariant();

                            string exif        = string.Empty;
                            string exifoutline = string.Empty;
                            if (File.Exists(filename))
                            {
                                using (ExifMetadata extractor = new ExifMetadata())
                                {
                                    ExifMetadata.Metadata metaData = extractor.GetExifMetadata(filename);

                                    if (!metaData.IsEmpty())
                                    {
                                        exif        = metaData.ToString();
                                        exifoutline = metaData.ToShortString();
                                    }
                                }
                            }

                            latestPictures.Add(new Latest()
                            {
                                DateTimeAdded  = pictures[i].DateTaken,
                                Title          = title,
                                Subtitle       = exifoutline,
                                Thumb          = thumb,
                                Fanart         = filename,
                                Classification = exif,
                                IsNew          = isnew
                            });

                            latestPicturesFiles.Add(i0, filename);
                            Utils.ThreadToSleep();

                            x++;
                            i0++;
                            if (x == Utils.FacadeMaxNum)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("GetLatestPictures: " + ex.ToString());
            }
            return(latestPictures);
        }