Esempio n. 1
1
        internal static BitmapSource ApplyOrientation(BitmapSource bitmap, BitmapMetadata metadata)
        {
            if (metadata == null || !metadata.ContainsQuery("System.Photo.Orientation"))
                return bitmap;

            ushort orientation = (ushort)metadata.GetQuery("System.Photo.Orientation");

            switch (orientation)
            {
                case 2: // flip horizontal
                    return new TransformedBitmap(bitmap, new ScaleTransform(-1, 1));

                case 3: // rotate 180
                    return new TransformedBitmap(bitmap, new RotateTransform(-180));

                case 4: // flip vertical
                    return new TransformedBitmap(bitmap, new ScaleTransform(1, -1));

                case 5: // transpose
                    bitmap = new TransformedBitmap(bitmap, new ScaleTransform(1, -1));
                    goto case 8;

                case 6: // rotate 270
                    return new TransformedBitmap(bitmap, new RotateTransform(-270));

                case 7: // transverse
                    bitmap = new TransformedBitmap(bitmap, new ScaleTransform(-1, 1));
                    goto case 8;

                case 8: // rotate 90
                    return new TransformedBitmap(bitmap, new RotateTransform(-90));

                default:
                    return bitmap;
            }
        }
Esempio n. 2
0
 private static short getOrientation(BitmapMetadata metadata)
 {
     try {
         ushort?orientationProp;
         if (metadata.ContainsQuery(JpegOrientationQuery))
         {
             orientationProp = metadata.GetQuery(JpegOrientationQuery) as ushort?;
         }
         else if (metadata.ContainsQuery(RawOrientationQuery))
         {
             orientationProp = metadata.GetQuery(RawOrientationQuery) as ushort?;
         }
         else
         {
             return(1);
         }
         if (orientationProp.HasValue)
         {
             return((short)orientationProp.Value);
         }
     } catch (ArgumentException) {
         return(1);
     }
     return(1);
 }
Esempio n. 3
0
        private static BitmapMetadata GetEXIFMetadata(BitmapMetadata metadata, string format)
        {
            BitmapMetadata exif = null;

            // GIF and PNG files do not contain EXIF meta data.
            if (format != "gif" && format != "png")
            {
                try
                {
                    if (format == "jpg")
                    {
                        exif = metadata.GetQuery("/app1/ifd/exif") as BitmapMetadata;
                    }
                    else
                    {
                        exif = metadata.GetQuery("/ifd/exif") as BitmapMetadata;
                    }
                }
                catch (IOException)
                {
                    // WINCODEC_ERR_INVALIDQUERYREQUEST
                }
            }

            return(exif);
        }
Esempio n. 4
0
        public static ushort[][] LoadPNG16WithMetadata(string filename, out string metaData)
        {
            ushort[][] result = null;
            // Open a Stream and decode a PNG image
            using (Stream imageStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                PngBitmapDecoder decoder      = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                BitmapSource     bitmapSource = decoder.Frames[0];
                if (bitmapSource.Format == System.Windows.Media.PixelFormats.Gray16)
                {
                    int    w      = bitmapSource.PixelWidth;
                    int    h      = bitmapSource.PixelHeight;
                    int    stride = w * 2;
                    byte[] ba     = new byte[h * stride];
                    bitmapSource.CopyPixels(ba, stride, 0);
                    result = JaggedArray <ushort> .A2(h, w);

                    int i = 0;
                    for (int y = 0; y < h; y++)
                    {
                        for (int x = 0; x < w; x++)
                        {
                            result[y][x] = (ushort)(ba[i++] + 256 * ba[i++]);
                        }
                    }
                }
                BitmapMetadata metadata = (BitmapMetadata)decoder.Frames[0].Metadata;
                if (metadata.GetQuery("/text/WaferData") == null)
                {
                    throw new Exception("There is no metadata in the image: " + filename);
                }
                metaData = metadata.GetQuery("/text/WaferData").ToString();
            }
            return(result);
        }
Esempio n. 5
0
        public void GetDataFromImage(String path, string oldpath)
        {
            string  folderpath = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName;
            string  filename   = "document.json";
            JObject rss        = JObject.Parse(File.ReadAllText(Path.Combine(folderpath, filename)));
            JObject channel    = (JObject)rss["photolist"];
            JArray  or         = (JArray)channel["photoor"];

            for (int i = 0; i < or.Count; i++)
            {
                if (or[i].ToString() == ("file:\\" + path))
                {
                    return;
                }
            }
            try
            {
                using (var Foto1 = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Inheritable))
                {
                    BitmapDecoder  decoder     = JpegBitmapDecoder.Create(Foto1, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default); //"распаковали" снимок и создали объект decoder
                    BitmapMetadata TmpImgEXIF2 = (BitmapMetadata)decoder.Frames[0].Metadata.Clone();                                                 //считали и сохранили метаданные
                                                                                                                                                     //result = (String)TmpImgEXIF2.GetQuery("/app1/ifd/gps/{ushort=2}");
                    ulong[] a     = ((ulong[])(TmpImgEXIF2.GetQuery("/app1/ifd/gps/{ushort=2}")));
                    ulong[] b     = ((ulong[])(TmpImgEXIF2.GetQuery("/app1/ifd/gps/{ushort=4}")));
                    double  aa    = obr(a[0]) + obr(a[1]) / 60 + obr(a[2]) / 3600;
                    double  bb    = obr(b[0]) + obr(b[1]) / 60 + obr(b[2]) / 3600;
                    string  path2 = Path.Combine(folderpath, "photosm");
                    Image   im    = Image.FromStream(Foto1);
                    im    = ResizeImg(im, 60, 60 * im.Height / im.Width);
                    path2 = Path.Combine(path2, GetRightPartOfPath(path, Path.GetFileName(oldpath)));
                    Directory.CreateDirectory(path2);
                    //     im.Save(path2 + "\\" + Path.GetFileName(path) + "small.jpg");
                    Bitmap bitmap = new Bitmap(im);
                    using (Graphics g = Graphics.FromImage(bitmap))
                    {
                        g.DrawRectangle(new Pen(Brushes.Yellow, 3), new Rectangle(0, 0, bitmap.Width - 1, bitmap.Height - 1));
                    }
                    string fname = Path.GetFileName(path);
                    fname = fname.Substring(0, fname.Length - 4) + "_small.jpg";
                    bitmap.Save(path2 + "\\" + fname);
                    JArray sm   = (JArray)channel["photosm"];
                    JArray tag1 = (JArray)channel["geotag1"];
                    JArray tag2 = (JArray)channel["geotag2"];
                    JArray h    = (JArray)channel["height"];
                    JArray w    = (JArray)channel["width"];
                    or.Add("file:\\" + path);
                    sm.Add("file:\\" + path2 + "\\" + fname);
                    tag1.Add(aa);
                    tag2.Add(bb);
                    h.Add(650 * im.Height / im.Width);
                    w.Add(650);
                    File.WriteAllText((Path.Combine(folderpath, filename)), rss.ToString());
                }
            }

            catch (Exception ex)
            {
            }
        }
Esempio n. 6
0
        private static BitmapMetadata GetXMPMetadata(BitmapMetadata metadata, string format)
        {
            BitmapMetadata xmp = null;

            // GIF files do not contain frame level XMP meta data.
            if (format != "gif")
            {
                try
                {
                    if (format == "png")
                    {
                        BitmapMetadata textChunk = metadata.GetQuery("/iTXt") as BitmapMetadata;

                        if (textChunk != null)
                        {
                            string keyWord = textChunk.GetQuery("/Keyword") as string;

                            if ((keyWord != null) && keyWord == "XML:com.adobe.xmp")
                            {
                                string data = textChunk.GetQuery("/TextEntry") as string;

                                if (!string.IsNullOrEmpty(data))
                                {
                                    xmp = LoadPNGMetadata(data);
                                }
                            }
                        }
                    }
                    else if (format == "jpg")
                    {
                        xmp = metadata.GetQuery("/xmp") as BitmapMetadata;
                    }
                    else
                    {
                        try
                        {
                            xmp = metadata.GetQuery("/ifd/xmp") as BitmapMetadata;
                        }
                        catch (IOException)
                        {
                            // WINCODEC_ERR_INVALIDQUERYREQUEST
                        }

                        if (xmp == null)
                        {
                            // Some codecs may store the XMP data outside of the IFD block.
                            xmp = metadata.GetQuery("/xmp") as BitmapMetadata;
                        }
                    }
                }
                catch (IOException)
                {
                    // WINCODEC_ERR_INVALIDQUERYREQUEST
                }
            }

            return(xmp);
        }
Esempio n. 7
0
        private void Load(Stream stream)
        {
            GifBitmapDecoder decoder = new GifBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

            _width  = decoder.Frames[0].PixelWidth;
            _height = decoder.Frames[0].PixelHeight;
            _frames = new GifFrame[decoder.Frames.Count];

            int duration = 0;

            for (int index = 0; index < decoder.Frames.Count; index++)
            {
                BitmapFrame    frame    = decoder.Frames[index].GetAsFrozen() as BitmapFrame;
                BitmapMetadata metadata = frame.Metadata as BitmapMetadata;
                int            delay    = (UInt16)metadata.GetQuery("/grctlext/Delay") * 10;

                if (delay < 60)
                {
                    delay = 100;
                }

                UInt16 left   = (UInt16)metadata.GetQuery("/imgdesc/Left");
                UInt16 top    = (UInt16)metadata.GetQuery("/imgdesc/Top");
                int    width  = frame.PixelWidth;
                int    height = frame.PixelHeight;

                _frames[index] = new GifFrame
                {
                    Image  = frame,
                    Height = height,
                    Left   = left,
                    Top    = top,
                    Width  = width,
                    Delay  = delay
                };

                duration += delay;
            }

            List <int> delays = _frames.Select(f => f.Delay).Distinct().ToList();

            if (delays.Count != 1)
            {
                Debug.WriteLine(String.Join(" ", delays));
            }

            Duration = TimeSpan.FromMilliseconds(duration);
        }
Esempio n. 8
0
        static public DateTime GetExif(string path)
        {
            DateTime dateOfImage = Convert.ToDateTime("01/01/1900");
            string   exiftitle;
            string   title;

            try
            {
                using (FileStream file = File.Open(path, FileMode.Open, FileAccess.Read))
                {
                    BitmapDecoder  decoder  = JpegBitmapDecoder.Create(file, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default);
                    BitmapMetadata metadata = (BitmapMetadata)decoder.Frames[0].Metadata.Clone();
                    //  title = metadata.Title;
                    dateOfImage = Convert.ToDateTime(metadata.DateTaken);
                    if (dateOfImage.ToString().Substring(0, 10) == "01.01.0001")
                    {
                        dateOfImage = System.IO.File.GetCreationTime(path);
                    }

                    exiftitle = (string)metadata.GetQuery(@"/app1/ifd/{ushort=40091}");
                }
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return(dateOfImage);
        }
Esempio n. 9
0
        public static bool TryGetQueryAs <TValue>(this BitmapMetadata metadata, string query, out TValue result)
        {
            if (!metadata.ContainsQuery(query))
            {
                result = default(TValue);
                return(false);
            }

            var value = metadata.GetQuery(query);

            if (value is TValue typedValue)
            {
                result = typedValue;
                return(true);
            }

            try
            {
                result = (TValue)Convert.ChangeType(value, typeof(TValue));
                return(true);
            }
            catch (Exception ex)
            {
                LogEx.For(typeof(ImageMetadataEx)).Error(
                    ex, "Failed to convert {Value} to {Type}",
                    value, typeof(TValue));

                result = default(TValue);
                return(false);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Метод возвращающий - Цветовое пространство
        /// </summary>
        /// <param name="TmpImgEXIF">Метаданные типа BitmapMetadata</param>
        /// <returns></returns>
        public string GetColorSpace(BitmapMetadata TmpImgEXIF)
        {
            //ПРЕДСТАВЛЕНИЯ ЦВЕТА
            //1 = sRGB
            //FFFF.H = Uncalibrated
            //Other = reserved
            try
            {
                int    t      = Convert.ToInt32(TmpImgEXIF.GetQuery("/app1/ifd/exif/{ushort=40961}"));
                string rezult = "";
                switch (t)
                {
                case 1:
                    rezult = "sRGB";
                    break;

                case 65535:
                    rezult = "Некалиброванный";
                    break;
                }
                return(rezult);
            }
            catch
            {
                return("");
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Метод возвращающий - Насыщенность
        /// </summary>
        /// <param name="TmpImgEXIF">Метаданные типа BitmapMetadata</param>
        /// <returns></returns>
        public string GetSaturation(BitmapMetadata TmpImgEXIF)
        {
            //насыщенность
            //0 = Normal
            //1 = Low saturation
            //2 = High saturation
            //Other = reserved
            try
            {
                int    t      = Convert.ToInt32(TmpImgEXIF.GetQuery("/app1/ifd/exif/{ushort=41993}")); // насыщенность
                string rezult = "";
                switch (t)
                {
                case 0:
                    rezult = "Обычная насыщенность";
                    break;

                case 1:
                    rezult = "Низкая насыщенность";
                    break;

                case 2:
                    rezult = "Высокая насыщенность";
                    break;
                }
                return(rezult);
            }
            catch
            {
                return("");
            }
        }
Esempio n. 12
0
 /// <summary>
 /// Метод возвращающий - Значение диафрагмы
 /// </summary>
 /// <param name="TmpImgEXIF">Метаданные типа BitmapMetadata</param>
 /// <returns>Значение диафрагмы || пустота</returns>
 public string GetFNumber(BitmapMetadata TmpImgEXIF)
 {
     try
     {
         var    t   = TmpImgEXIF.GetQuery("/app1/ifd/exif/{ushort=33437}");
         var    mss = ObjectToByteArray(t);
         string pv0 = Convert.ToInt32(mss[50]).ToString();
         if (pv0.Length == 1)
         {
             return("1." + pv0);
         }
         if (pv0.Length == 3)
         {
             pv0 = pv0.Substring(0, 2);
         }
         if (pv0.Length == 2 && !pv0.StartsWith("1"))
         {
             pv0 = pv0.Substring(0, pv0.Length - 1) + "." + pv0.Substring(pv0.Length - 1, 1);
         }
         pv0 = pv0.Replace(".0", "");
         return("f/" + pv0);
     }
     catch
     {
         return("");
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Метод возвращающий - Рейтинг фотографии
        /// </summary>
        /// <param name="TmpImgEXIF">Метаданные типа BitmapMetadata</param>
        /// <returns></returns>
        public string GetRating(BitmapMetadata TmpImgEXIF)
        {
            try
            {
                int flash = Convert.ToInt32(TmpImgEXIF.GetQuery("/app1/ifd/{ushort=18249}"));
                // rating фотографии 1 звезда = 1 , 2звезды = 25, 3 - 50, 4 - 75, 5 - 100
                string val = "";
                switch (flash)
                {
                case 1: val = "1/5"; break;

                case 25: val = "2/5"; break;

                case 50: val = "3/5"; break;

                case 75: val = "4/5"; break;

                case 100: val = "5/5"; break;
                }
                return(val);
            }
            catch (Exception)
            {
                return("");
            }
        }
Esempio n. 14
0
 private static void CreateTree(Node parent, BitmapMetadata metadata)
 {
     foreach (string query in metadata)
     {
         object value = null;
         try
         {
             value = metadata.GetQuery(query);
         }
         catch (ArgumentException)
         {
             continue;
         }
         var node = new Node();
         node.Parent = parent;
         node.Path   = parent.Path;
         node.Query  = query;
         parent.Children.Add(node);
         if (value is BitmapMetadata)
         {
             CreateTree(node, value as BitmapMetadata);
         }
         else
         {
             node.Value = ConvertValue(value);
         }
         node.Type = value.GetType();
     }
 }
Esempio n. 15
0
        private Double GetRotation(string path)
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                BitmapFrame    bitmapFrame    = BitmapFrame.Create(fileStream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
                BitmapMetadata bitmapMetadata = bitmapFrame.Metadata as BitmapMetadata;

                if ((bitmapMetadata != null) && (bitmapMetadata.ContainsQuery(_orientationQuery)))
                {
                    object o = bitmapMetadata.GetQuery(_orientationQuery);

                    if (o != null)
                    {
                        //refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values
                        switch ((ushort)o)
                        {
                        case 6:
                            return(90D);

                        case 3:
                            return(180D);

                        case 8:
                            return(270D);
                        }
                    }
                }
                return(0D);
            }
        }
Esempio n. 16
0
        private int GetRotation(BitmapMetadata metadata)
        {
            int rotation = 0;

            if ((metadata != null) && metadata.ContainsQuery("System.Photo.Orientation"))
            {
                object o = metadata.GetQuery("System.Photo.Orientation");

                if (o != null)
                {
                    //refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values
                    switch ((ushort)o)
                    {
                    case 6:
                        rotation = 90;
                        break;

                    case 3:
                        rotation = 180;
                        break;

                    case 8:
                        rotation = 270;
                        break;
                    }
                }
            }

            return(rotation);
        }
        private static void CaptureMetadata(ImageMetadata imageMetadata, string query, List <RawMetadataItem> dataItems)
        {
            if (dataItems == null)
            {
                dataItems = new List <RawMetadataItem>();
            }

            BitmapMetadata bitmapMetadata = imageMetadata as BitmapMetadata;

            if (bitmapMetadata != null)
            {
                foreach (string relativeQuery in bitmapMetadata)
                {
                    string fullQuery           = query + relativeQuery;
                    object metadataQueryReader = bitmapMetadata.GetQuery(relativeQuery);

                    if (relativeQuery != "/ifd" && relativeQuery.IndexOf("/{ushort=") == 0)
                    {
                        RawMetadataItem metadataItem = new RawMetadataItem();
                        Int32.TryParse(relativeQuery.Substring(9).TrimEnd('}'), out metadataItem.location);
                        metadataItem.value = metadataQueryReader;
                        dataItems.Add(metadataItem);
                    }

                    BitmapMetadata innerBitmapMetadata = metadataQueryReader as BitmapMetadata;
                    if (innerBitmapMetadata != null)
                    {
                        CaptureMetadata(innerBitmapMetadata, fullQuery, dataItems);
                    }
                }
            }
        }
Esempio n. 18
0
        private static byte[] ExtractXMPPacket(BitmapMetadata xmp)
        {
            BitmapMetadata tiffMetaData = new BitmapMetadata("tiff");

            tiffMetaData.SetQuery("/ifd/xmp", new BitmapMetadata("xmp"));

            foreach (string tag in xmp)
            {
                object value = xmp.GetQuery(tag);

                if (value is BitmapMetadata xmpSub)
                {
                    CopySubIFDRecursive(ref tiffMetaData, xmpSub, "/ifd/xmp" + tag);
                }
                else
                {
                    tiffMetaData.SetQuery("/ifd/xmp" + tag, value);
                }
            }

            byte[] xmpBytes = null;

            using (MemoryStream stream = new MemoryStream())
            {
                // Create a dummy tiff to extract the XMP packet from.
                BitmapSource      source  = BitmapSource.Create(1, 1, 96.0, 96.0, PixelFormats.Gray8, null, new byte[] { 255 }, 1);
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source, null, tiffMetaData, null));
                encoder.Save(stream);

                xmpBytes = TiffReader.ExtractXMP(stream);
            }

            return(xmpBytes);
        }
Esempio n. 19
0
        /// <summary>
        /// Get the metadata item recursively
        /// </summary>
        /// <param name="bitmapMetadata"></param>
        /// <param name="itemMap"></param>
        /// <param name="filter"></param>
        /// <param name="query"></param>
        private static void GetMetaDataItems(BitmapMetadata bitmapMetadata, ref Dictionary <string, string> itemMap, string filter = null, string query = null)
        {
            if (query == null)
            {
                query = string.Empty;
            }

            if (bitmapMetadata != null)
            {
                var key = string.Empty;

                foreach (string relativeQuery in bitmapMetadata)
                {
                    var fullQuery = query + relativeQuery;
                    // GetQuery returns an object: either a string or child metadata
                    // If a string then it is one of 4 values: ["Keyword", "Translated", "Compression", "Language Tag", "TextEntry"]
                    // We want the Keyword and the subsequent TextEntry items, the tags are a sequence in the order specified above
                    var metadata            = bitmapMetadata.GetQuery(relativeQuery);
                    var innerBitmapMetadata = metadata as BitmapMetadata;

                    if (innerBitmapMetadata == null)
                    {
                        AddToMap(ref key, fullQuery, metadata.ToString(), ref itemMap, filter);    // Not a metadata structure so it is data - therefore check and Add to map
                    }
                    else
                    {
                        GetMetaDataItems(innerBitmapMetadata, ref itemMap, filter, fullQuery);      // Recursive call
                    }
                }
            }
        }
Esempio n. 20
0
 private static T GetQueryOrDefault <T>(
     this BitmapMetadata metadata,
     string query,
     T defaultValue)
 {
     return(metadata.ContainsQuery(query) ? (T)Convert.ChangeType(metadata.GetQuery(query), typeof(T), (IFormatProvider)CultureInfo.InvariantCulture) : defaultValue);
 }
Esempio n. 21
0
        private static TimeSpan GetFrameDelay(BitmapFrame frame)
        {
            // 100ms by default if the value is not defined in metadata
            TimeSpan duration = TimeSpan.FromMilliseconds(100);

            BitmapMetadata metaData = null;

            try
            {
                metaData = frame.Metadata as BitmapMetadata;
                if (metaData != null)
                {
                    const string query = "/grctlext/Delay";
                    if (metaData.ContainsQuery(query))
                    {
                        object o = metaData.GetQuery(query);
                        if (o != null)
                        {
                            ushort delay = (ushort)o;
                            duration = TimeSpan.FromMilliseconds(10 * delay);
                        }
                    }
                }
            }
            catch (NotSupportedException)
            {
            }

            return(duration);
        }
    public Transformations(BitmapMetadata md)
    {
        // https://docs.microsoft.com/en-us/windows/win32/wic/-wic-photoprop-system-photo-orientation
        // https://docs.microsoft.com/en-us/windows/win32/properties/props-system-photo-orientation
        const string orientationProperty = "System.Photo.Orientation";

        if (md != null && md.ContainsQuery(orientationProperty))
        {
            var orientation = (Orientation)md.GetQuery(orientationProperty);
            switch (orientation)
            {
            case Orientation.FlipHorizontal:
                FlipHorizontal = true;
                break;

            case Orientation.FlipVertical:
                FlipVertical = true;
                break;

            case Orientation.Rotate90:
                Rotation = Rotation.Rotate90;
                break;

            case Orientation.Rotate180:
                Rotation = Rotation.Rotate180;
                break;

            case Orientation.Rotate270:
                Rotation = Rotation.Rotate270;
                break;
                // we don't support transpose & transverse
            }
        }
    }
        public static Rotation GetRotation(BitmapSource bitmapSource)
        {
            BitmapMetadata bitmapMetadata = bitmapSource.Metadata as BitmapMetadata;

            if ((bitmapMetadata != null) && (bitmapMetadata.ContainsQuery(OrientationQuery)))
            {
                object o = bitmapMetadata.GetQuery(OrientationQuery);

                if (o != null)
                {
                    //refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values
                    switch ((ushort)o)
                    {
                        case 6:
                            return Rotation.Rotate90;
                        case 3:
                            return Rotation.Rotate180;
                        case 8:
                            return Rotation.Rotate270;
                    }
                }
            }

            return Rotation.Rotate0;
        }
Esempio n. 24
0
        public static bool IsQueryValidAndOfType(this BitmapMetadata bitmapMetadata, string query, Type type)
        {
            // Check there's a query value
            if (bitmapMetadata.ContainsQuery(query))
            {
                type = bitmapMetadata.GetStorageType(type);

                // Get object
                Object obj = bitmapMetadata.GetQuery(query).GetType();

                if (obj != null)
                {
                    // Special case for empty strings, return true if set
                    // Otherwise check for null and then type
                    if (type == typeof(string))
                    {
                        return(true);
                    }
                    else if (obj == type)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
            static Rotation GetRotation(string filename)
            {
                BitmapFrame    bitmapFrame    = BitmapFrame.Create(new Uri(filename), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
                BitmapMetadata bitmapMetadata = bitmapFrame.Metadata as BitmapMetadata;

                if (bitmapMetadata == null || !bitmapMetadata.ContainsQuery("System.Photo.Orientation"))
                {
                    return(Rotation.Rotate0);
                }

                //refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values
                switch (bitmapMetadata.GetQuery("System.Photo.Orientation") as ushort?)
                {
                case 6:
                    return(Rotation.Rotate90);

                case 3:
                    return(Rotation.Rotate180);

                case 8:
                    return(Rotation.Rotate270);

                default:
                    return(Rotation.Rotate0);
                }
            }
Esempio n. 26
0
        private IEnumerable ProcessArray(BitmapMetadata metadata, int depth)
        {
            ArrayList array = new ArrayList();

            foreach (string name in this.GetNamesSafely(metadata))
            {
                object value = metadata.GetQuery(name);

#if DIAGNOSTICS
                Console.Write(new String('\t', depth));
                Console.WriteLine("{0} => {1}: {2}", name, value != null ? value.GetType().Name : "null", Convert.ToString(value));
#endif

                if (value is BitmapMetadata)
                {
                    value = this.ProcessMetadata((BitmapMetadata)value, name, depth);
                }
                else if (value is BitmapMetadataBlob)
                {
                    value = ((BitmapMetadataBlob)value).GetBlobValue();
                }

                if (value == null)
                {
                    continue;
                }

                array.Add(value);
            }

            return(array);
        }
Esempio n. 27
0
        private float?GetLongitude(BitmapMetadata bitmapMetadata)
        {
            using (var logger = _logger.Block()) {
                logger.Trace("Checking if file has longitude information...");
                if (!(bitmapMetadata.GetQuery("System.GPS.Longitude.Proxy") is string longitudeRef))
                {
                    logger.Trace("File does not have longitude information.  Exiting...");
                    return(null);
                }

                logger.Trace($"Parsing longitude information \"{longitudeRef}\"...");
                var longitudeMatch = Regex.Match(longitudeRef, @"^(\d+),([0123456789.]+)([EW])");
                if (!longitudeMatch.Success)
                {
                    logger.Trace($"Unable to parse \"{longitudeRef}\".  Exiting...");
                    return(null);
                }

                logger.Trace("Converting to a float...");
                var longitudeDecimal = float.Parse(longitudeMatch.Groups[1].Value) + float.Parse(longitudeMatch.Groups[2].Value) / 60;
                if (longitudeMatch.Groups[3].Value == "W")
                {
                    longitudeDecimal *= -1;
                }

                return(longitudeDecimal);
            }
        }
Esempio n. 28
0
        private void CaptureMetadata(List <MetadataItem> result, ImageMetadata imageMetadata, string query)
        {
            BitmapMetadata bitmapMetadata = imageMetadata as BitmapMetadata;

            if (bitmapMetadata != null)
            {
                foreach (string relativeQuery in bitmapMetadata)
                {
                    string fullQuery = query + relativeQuery;
                    object resp      = bitmapMetadata.GetQuery(relativeQuery);

                    MetadataDefinition defn = new MetadataDefinition()
                    {
                        Category = "Category",
                        Name     = resp.GetType().ToString(),
                        Path     = fullQuery
                    };

                    MetadataItem metadataItem = new MetadataItem(defn, resp);
                    result.Add(metadataItem);
                    BitmapMetadata innerBitmapMetadata = resp as BitmapMetadata;
                    if (innerBitmapMetadata != null)
                    {
                        CaptureMetadata(result, innerBitmapMetadata, fullQuery);
                    }
                }
            }
        }
Esempio n. 29
0
        private static string readString(BitmapMetadata metadata, string key)
        {
            var md = metadata.GetQuery(key);

            switch (md)
            {
            case string direct:
                if (key.StartsWith("/xmp/"))
                {
                    return(direct);
                }
                else
                {
                    return(Encoding.UTF8.GetString(Encoding.Default.GetBytes(direct)));
                }

            case BitmapMetadata indirect:
                foreach (string query in indirect)
                {
                    return(readString(indirect, key + query));
                }
                return(null);

            case byte[] bytes:
                return(Encoding.Unicode.GetString(bytes));

            default:
                return(null);
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Loads the PNG XMP meta data using a dummy TIFF.
        /// </summary>
        /// <param name="xmp">The XMP string to load.</param>
        /// <returns>The loaded XMP block, or null.</returns>
        private static BitmapMetadata LoadPNGMetadata(string xmp)
        {
            BitmapMetadata xmpData = null;

            using (MemoryStream stream = new MemoryStream())
            {
                // PNG stores the XMP meta-data in an iTXt chunk as an UTF8 encoded string,
                // so we have to save it to a dummy tiff and grab the XMP meta-data on load.
                BitmapMetadata tiffMetadata = new BitmapMetadata("tiff");
                tiffMetadata.SetQuery("/ifd/xmp", new BitmapMetadata("xmp"));
                tiffMetadata.SetQuery("/ifd/xmp", Encoding.UTF8.GetBytes(xmp));

                BitmapSource      source  = BitmapSource.Create(1, 1, 96.0, 96.0, PixelFormats.Gray8, null, new byte[] { 255 }, 1);
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source, null, tiffMetadata, null));
                encoder.Save(stream);

                TiffBitmapDecoder dec = new TiffBitmapDecoder(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);

                if (dec.Frames.Count == 1)
                {
                    BitmapMetadata meta = dec.Frames[0].Metadata as BitmapMetadata;
                    if (meta != null)
                    {
                        xmpData = meta.GetQuery("/ifd/xmp") as BitmapMetadata;
                    }
                }
            }

            return(xmpData);
        }
Esempio n. 31
0
        /// <summary>
        /// Gets the IPTC caption of the image.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <returns>The IPTC caption or null.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="image"/> is null.
        /// </exception>
        internal static string GetIPTCCaption(BitmapSource image)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            BitmapMetadata metadata = null;

            try
            {
                metadata = image.Metadata as BitmapMetadata;
            }
            catch (NotSupportedException)
            {
            }

            if (metadata != null)
            {
                string iptcCaption = null;

                try
                {
                    iptcCaption = metadata.GetQuery("/ifd/iptc/{str=Caption}") as string;
                }
                catch (IOException)
                {
                    // WINCODEC_ERR_INVALIDQUERYREQUEST
                }

                if (iptcCaption == null)
                {
                    try
                    {
                        iptcCaption = metadata.GetQuery("/ifd/xmp/dc:description/x-default") as string;
                    }
                    catch (IOException)
                    {
                        // WINCODEC_ERR_INVALIDQUERYREQUEST
                    }
                }

                return(iptcCaption);
            }

            return(null);
        }
        private static void AddIptcMetadata(BitmapMetadata bmpMetadata, IGalleryObjectMetadataItemCollection metadataItems)
        {
            foreach (KeyValuePair<FormattedMetadataItemName, string> iptcQueryParm in GetIptcQueryParameters())
            {
                string iptcValue = bmpMetadata.GetQuery(String.Format(CultureInfo.InvariantCulture, IptcQueryFormatString, iptcQueryParm.Value)) as string;

                if (!String.IsNullOrEmpty(iptcValue))
                {
                    switch (iptcQueryParm.Key)
                    {
                        case FormattedMetadataItemName.IptcDateCreated:
                            {
                                DateTime dateTaken = TryParseDate(iptcValue);

                                if (dateTaken.Year > DateTime.MinValue.Year)
                                {
                                    metadataItems.AddNew(int.MinValue, iptcQueryParm.Key, GetResource(iptcQueryParm.Key), dateTaken.ToString(DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true);
                                }
                                break;
                            }
                        default:
                            {
                                metadataItems.AddNew(int.MinValue, iptcQueryParm.Key, GetResource(iptcQueryParm.Key), iptcValue, true);
                                break;
                            }
                    }
                }
            }
        }
Esempio n. 33
0
 private static BitmapSource MetaOrientation(BitmapMetadata meta, BitmapSource ret)
 {
     double angle = 0.0;
       if (meta != null && ret != null)
       {
     if (meta.GetQuery("/app1/ifd/{ushort=274}") != null)
       Picture.orientation = (Picture.ExifOrientations)Enum.Parse(typeof(Picture.ExifOrientations), meta.GetQuery("/app1/ifd/{ushort=274}").ToString());
     switch (Picture.orientation)
     {
       case Picture.ExifOrientations.Rotate180:
     angle = 180.0;
     break;
       case Picture.ExifOrientations.Rotate270:
     angle = 90.0;
     break;
       case Picture.ExifOrientations.Rotate90:
     angle = -90.0;
     break;
     }
     if (angle != 0.0)
     {
       ret = (BitmapSource)new TransformedBitmap(ret.Clone(), (Transform)new RotateTransform(angle));
       ret.Freeze();
     }
       }
       return ret;
 }
Esempio n. 34
0
    private static BitmapSource MetaOrientation(BitmapMetadata meta, BitmapSource ret)
    {
      double angle = 0;
      if ((meta != null) && (ret != null)) //si on a des meta, tentative de récupération de l'orientation
      {
        if (meta.GetQuery("/app1/ifd/{ushort=274}") != null)
        {
          orientation =
            (ExifOrientations)
            Enum.Parse(typeof (ExifOrientations), meta.GetQuery("/app1/ifd/{ushort=274}").ToString());
        }

        switch (orientation)
        {
          case ExifOrientations.Rotate90:
            angle = -90;
            break;
          case ExifOrientations.Rotate180:
            angle = 180;
            break;
          case ExifOrientations.Rotate270:
            angle = 90;
            break;
        }

        if (angle != 0) //on doit effectuer une rotation de l'image
        {
          ret = new TransformedBitmap(ret.Clone(), new RotateTransform(angle));
          ret.Freeze();
        }
      }
      return ret;
    }
Esempio n. 35
0
        protected void EnumerateMetaData( BitmapMetadata _Root, params MetaDataProcessor[] _Processors )
        {
            foreach ( MetaDataProcessor Processor in _Processors )
            {
                if ( !_Root.ContainsQuery( Processor.Path ) )
                    continue;

                object	Value = _Root.GetQuery( Processor.Path );
                if ( Value == null )
                    throw new Exception( "Failed to find the metadata path \"" + Processor.Path + "\" !" );

                Processor.Process( Value );
            }
        }
Esempio n. 36
0
 /// <summary>
 /// Invokes the <see cref="BitmapMetadata.GetQuery" /> method on <paramref name="bmpMetadata" />, passing in the specified
 /// <paramref name="query" />. Any <see cref="NotSupportedException" /> exceptions are silently swallowed.
 /// </summary>
 /// <param name="bmpMetadata">An object containing the metadata.</param>
 /// <param name="query">The query to execute against <paramref name="bmpMetadata" />.</param>
 /// <returns></returns>
 private static object GetQuery(BitmapMetadata bmpMetadata, string query)
 {
     try
     {
         return bmpMetadata.GetQuery(query);
     }
     catch (NotSupportedException)
     {
         return null;
     }
 }
 /// <summary>
 /// Returns the metadata for the given query.
 /// </summary>
 /// <param name="metadata">The image metadata.</param>
 /// <param name="query">A list of query strings.</param>
 /// <returns>Metadata object or null if the metadata is not found.</returns>
 private static object GetMetadataObject(BitmapMetadata metadata, params string[] query)
 {
     foreach (string q in query)
     {
         object val = metadata.GetQuery(q);
         if (val != null)
             return val;
     }
     return null;
 }
Esempio n. 38
0
    public bool WriteMetadata() {
      FileInfo original = new FileInfo(FilePath);
      FileInfo newFile = new FileInfo(FilePath + "_newFile");
      bool bSuccess = false;
      const BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;

      using (Stream originalFileStream = File.Open(original.FullName, FileMode.Open, FileAccess.Read)) {
        BitmapDecoder decoder = BitmapDecoder.Create(originalFileStream, createOptions, BitmapCacheOption.None);
        if (decoder.CodecInfo != null && decoder.CodecInfo.FileExtensions.Contains("jpg") && decoder.Frames[0] != null) {
          BitmapMetadata metadata = decoder.Frames[0].Metadata == null
            ? new BitmapMetadata("jpg")
            : decoder.Frames[0].Metadata.Clone() as BitmapMetadata;

          if (metadata != null) {

            //People
            const string microsoftRegionInfo = @"/xmp/MP:RegionInfo";
            const string microsoftRegions = @"/xmp/MP:RegionInfo/MPRI:Regions";
            const string microsoftPersonDisplayName = @"/MPReg:PersonDisplayName";
            int peopleIdx = -1;
            List<string> addedPeople = new List<string>();
            //New metadata just for People
            BitmapMetadata people = new BitmapMetadata("jpg");
            people.SetQuery(microsoftRegionInfo, new BitmapMetadata("xmpstruct"));
            people.SetQuery(microsoftRegions, new BitmapMetadata("xmpbag"));
            //Adding existing people
            BitmapMetadata existingPeople = metadata.GetQuery(microsoftRegions) as BitmapMetadata;
            if (existingPeople != null) {
              foreach (string idx in existingPeople) {
                var existingPerson = metadata.GetQuery(microsoftRegions + idx) as BitmapMetadata;
                var personDisplayName = existingPerson?.GetQuery(microsoftPersonDisplayName);
                if (personDisplayName == null) continue;
                if (!People.Any(p => p.Title.Equals(personDisplayName.ToString()))) continue;
                addedPeople.Add(personDisplayName.ToString());
                peopleIdx++;
                people.SetQuery($"{microsoftRegions}/{{ulong={peopleIdx}}}", existingPerson);
              }
            }
            //Adding new people
            foreach (Person person in People.Where(p => !addedPeople.Any(ap => ap.Equals(p.Title)))) {
              peopleIdx++;
              people.SetQuery($"{microsoftRegions}/{{ulong={peopleIdx}}}", new BitmapMetadata("xmpstruct"));
              people.SetQuery($"{microsoftRegions}/{{ulong={peopleIdx}}}" + microsoftPersonDisplayName, person.Title);
            }
            //Writing all people to MediaItem metadata
            var allPeople = people.GetQuery(microsoftRegionInfo);
            if (allPeople != null)
              metadata.SetQuery(microsoftRegionInfo, allPeople);


            metadata.Rating = Rating;
            metadata.Comment = Comment ?? string.Empty;
            metadata.Keywords = new ReadOnlyCollection<string>(Keywords.Select(k => k.FullPath).ToList());

            JpegBitmapEncoder encoder = new JpegBitmapEncoder { QualityLevel = Settings.Default.JpegQualityLevel };
            encoder.Frames.Add(BitmapFrame.Create(decoder.Frames[0], decoder.Frames[0].Thumbnail, metadata,
              decoder.Frames[0].ColorContexts));

            try {
              using (Stream newFileStream = File.Open(newFile.FullName, FileMode.Create, FileAccess.ReadWrite)) {
                encoder.Save(newFileStream);
              }
              bSuccess = true;
            }
            catch (Exception) {
              bSuccess = false;
            }
          }
        }
      }

      if (bSuccess) {
        newFile.CreationTime = original.CreationTime;
        original.Delete();
        newFile.MoveTo(original.FullName);
      }
      return bSuccess;
    }
Esempio n. 39
0
        protected string DumpMetaData( BitmapMetadata _Root, string _Tab )
        {
            string	Result = "";
            foreach ( string Meta in _Root.AsEnumerable<string>() )
            {
                Result += _Tab + Meta;

                object	Value = _Root.GetQuery( Meta );
                if ( Value is BitmapMetadata )
                {	// Recurse
                    _Tab += "\t";
                    Result += "\r\n" + DumpMetaData( Value as BitmapMetadata, _Tab );
                    _Tab = _Tab.Remove( _Tab.Length-1 );
                }
                else
                {	// Leaf
                    Result += " = " + Value + "\r\n";
                }
            }

            return Result;
        }
Esempio n. 40
0
 /// <summary>
 /// [PHAP] Returns the metadata for the given query.
 /// </summary>
 /// <param name="metadata">The image metadata.</param>
 /// <param name="query">A list of query strings.</param>
 /// <returns>Metadata object or null if the metadata is not found.</returns>
 private object GetMetadataObject(BitmapMetadata metadata, params string[] query)
 {
     try
     {
         foreach (string q in query)
         {
             object val = metadata.GetQuery(q);
             if (val != null)
                 return val;
         }
     }
     catch (Exception)
     {
         return null;
     }
     return null;
 }
        private void BlankMetaInfo(string query, BitmapMetadata metaData)
        {
            object obj = metaData.GetQuery(query);
            if (obj != null)
            {
                if (obj is string)
                    metaData.SetQuery(query, string.Empty);
                else
                {
                    ulong dummy;
                    if (ulong.TryParse(obj.ToString(), out dummy))
                    {
                        metaData.SetQuery(query, 0);
                    }

                }
            }
        }
Esempio n. 42
0
        public static Rotation? getOrientationFromMetatdata(BitmapMetadata meta)
        {
            if (meta != null)
            {
                UInt16 orientation = 1;
                Object result = meta.GetQuery("/app1/ifd/{ushort=274}");

                if (result != null)
                {
                    orientation = (UInt16)result;
                }
                else
                {
                    return (null);
                }

                switch (orientation)
                {
                    case 8:
                        return (Rotation.Rotate270);
                    case 3:
                        return (Rotation.Rotate180);
                    case 6:
                        return (Rotation.Rotate90);
                    default:
                        return (Rotation.Rotate0);

                }

            }
            else
            {
                return (null);
            }
        }
Esempio n. 43
0
        private int GetRotation(BitmapMetadata metadata)
        {
            int rotation = 0;

            if ((metadata != null) && metadata.ContainsQuery("System.Photo.Orientation"))
            {
                object o = metadata.GetQuery("System.Photo.Orientation");

                if (o != null)
                {
                    //refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values
                    switch ((ushort)o)
                    {
                        case 6:
                            rotation = 90;
                            break;
                        case 3:
                            rotation = 180;
                            break;
                        case 8:
                            rotation = 270;
                            break;
                    }
                }
            }

            return rotation;
        }
Esempio n. 44
0
        private void EnumerateMetaData(string keyprefix, BitmapMetadata meta)
        {
            foreach (var key in meta)
            {
                if (key == null) continue;

                object o = meta.GetQuery(key);

                if (o is BitmapMetadata) EnumerateMetaData(keyprefix + key, (BitmapMetadata)o);
                else Debug.WriteLine("{0}: {1}", keyprefix + key, o);
            }
        }