Beispiel #1
0
        /// <summary>
        /// Method to load picture from disk.
        /// </summary>
        /// <param name="filename">The full path file name of the picture.</param>
        /// <param name="width">The width of the image.</param>
        /// <param name="isHttp">Is Http filename Url ?.</param>
        /// <returns>A BitmapImage that contain the picture.</returns>
        public static BitmapImage GetPicture(string filename, int width = 512, bool isHttp = false)
        {
            // Initialize bitmap image.
            BitmapImage src = new BitmapImage();

            // Try to create bitmap image from picture.
            try
            {
                log.Debug($"{typeof(PictureMemoryCache).Name}.{MethodBase.GetCurrentMethod().Name} : Creating bitmap image from picture.");

                if (string.IsNullOrWhiteSpace(filename))
                {
                    ArgumentNullException e = new ArgumentNullException(nameof(filename));
                    log.Error(e.Output(), e);

                    return(src);
                }

                if (!Path.IsPathRooted(filename) && !isHttp)
                {
                    filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
                }

                if (!File.Exists(filename) && !isHttp)
                {
                    FileNotFoundException e = new FileNotFoundException("File not found :", filename);
                    log.Error(e.Output(), e);

                    return(src);
                }

                log.Debug($"{typeof(PictureMemoryCache).Name}.{MethodBase.GetCurrentMethod().Name} : {filename}");

                src.BeginInit();
                src.CacheOption      = BitmapCacheOption.OnLoad;
                src.CreateOptions    = BitmapCreateOptions.IgnoreImageCache | BitmapCreateOptions.PreservePixelFormat;
                src.UriSource        = new Uri(@filename, UriKind.Absolute);
                src.DecodePixelWidth = width;
                src.EndInit();

                // Freeze picture if possible.
                if (!src.IsFrozen && src.CanFreeze)
                {
                    src.Freeze();
                    log.Debug($"{typeof(PictureMemoryCache).Name}.{MethodBase.GetCurrentMethod().Name} : Freezing Picture => done.");
                }
            }

            // Catch create bitmap image fail.
            // Just log error but generate no new exception.
            catch (Exception e)
            {
                log.Error("PictureMemoryCache try to create bitmap image but operation failed !", e);
                log.Error("filename : " + filename);
            }

            return(src);
        }