Example #1
0
 /// <summary>
 /// If this decoder cannot handle the bitmap stream, it will throw an exception.
 /// </summary>
 /// <param name="bitmapStream">Stream to decode</param>
 /// <param name="createOptions">Bitmap Create Options</param>
 /// <param name="cacheOption">Bitmap Caching Option</param>
 public GifBitmapDecoder(
     Stream bitmapStream,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     ) : base(bitmapStream, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatGif)
 {
 }
        /// <summary>
        /// To the bitmap source.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        /// <param name="format">The format.</param>
        /// <param name="creationOptions">The creation options.</param>
        /// <param name="cacheOptions">The cache options.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">bitmap</exception>
        public static BitmapSource ToBitmapSource(this Bitmap bitmap, ImageFormat format, BitmapCreateOptions creationOptions = BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption cacheOptions = BitmapCacheOption.OnLoad)
        {
            if (bitmap == null)
                throw new ArgumentNullException("bitmap");

            using (MemoryStream memoryStream = new MemoryStream())
            {
                try
                {
                    // You need to specify the image format to fill the stream.
                    // I'm assuming it is PNG
                    bitmap.Save(memoryStream, format);
                    memoryStream.Seek(0, SeekOrigin.Begin);

                    BitmapDecoder bitmapDecoder = BitmapDecoder.Create(
                        memoryStream,
                        creationOptions,
                        cacheOptions);

                    // This will disconnect the stream from the image completely...
                    WriteableBitmap writable =
            new WriteableBitmap(bitmapDecoder.Frames.Single());
                    writable.Freeze();

                    return writable;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
Example #3
0
 public BitmapImage(Uri uriSource, BitmapCacheOption cacheOption = BitmapCacheOption.Default)
 {
     BeginInit();
     this.UriSource   = uriSource;
     this.CacheOption = cacheOption;
     EndInit();
 }
Example #4
0
        public static BitmapDecoder Create(
            Uri bitmapUri,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption)
        {
            Stream stream;

            if (!bitmapUri.IsAbsoluteUri)
            {
                stream = Application.GetResourceStream(bitmapUri).Stream;
            }
            else if (bitmapUri.IsFile)
            {
                stream = new FileStream(
                    Uri.UnescapeDataString(bitmapUri.AbsolutePath),
                    FileMode.Open,
                    FileAccess.Read);
            }
            else
            {
                throw new NotSupportedException("URI not yet supported.");
            }

            return(Create(stream, createOptions, cacheOption));
        }
Example #5
0
        //public static async void LoadImage(this Image image, string path) {
        //    var httpClient = new HttpClient();
        //    var a = await httpClient.GetByteArrayAsync(path);
        //}

        public static void LoadImage(this Image img, string path,
                                     EventHandler <ExceptionEventArgs> Failed         = null,
                                     EventHandler <DownloadProgressEventArgs> Loading = null,
                                     EventHandler Completed            = null,
                                     BitmapCreateOptions CreateOptions = BitmapCreateOptions.PreservePixelFormat,
                                     BitmapCacheOption CacheOption     = BitmapCacheOption.OnLoad)
        {
            Uri targetURI = new Uri(path);

            img.Tag = path;

            bool IsLocalFile = Path.GetPathRoot(path) != "";

            if (IsLocalFile)
            {
                var bs = new BitmapImage(targetURI);
                img.Source = bs;
                Completed(bs, null);
            }
            else
            {
                var bitmapSource = new BitmapImage(targetURI);
                bitmapSource.DownloadFailed    += Failed;
                bitmapSource.DownloadProgress  += Loading;
                bitmapSource.DownloadCompleted += Completed;
            }
        }
Example #6
0
        /// <summary> 
        /// Internal constructor -- Creates new frame using specified decoder 
        /// </summary>
        internal BitmapFrameDecode( 
            int frameNumber,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            BitmapDecoder decoder 
            ) : base(true)
        { 
            _bitmapInit.BeginInit(); 
            _frameNumber = frameNumber;
            _isThumbnailCached = false; 
            _isMetadataCached = false;
            _frameSource = null;

            Debug.Assert(decoder != null); 
            _decoder = decoder;
            _syncObject = decoder.SyncObject; 
            _createOptions = createOptions; 
            _cacheOption = cacheOption;
 
            _bitmapInit.EndInit();

            if ((createOptions & BitmapCreateOptions.DelayCreation) != 0)
            { 
                DelayCreation = true;
            } 
            else 
            {
                FinalizeCreation(); 
            }
        }
Example #7
0
        /// <summary>
        /// Internal constructor -- Creates new frame using specified decoder
        /// </summary>
        internal BitmapFrameDecode(
            int frameNumber,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            BitmapDecoder decoder
            ) : base(true)
        {
            _bitmapInit.BeginInit();
            _frameNumber       = frameNumber;
            _isThumbnailCached = false;
            _isMetadataCached  = false;
            _frameSource       = null;

            Debug.Assert(decoder != null);
            _decoder       = decoder;
            _syncObject    = decoder.SyncObject;
            _createOptions = createOptions;
            _cacheOption   = cacheOption;

            _bitmapInit.EndInit();

            if ((createOptions & BitmapCreateOptions.DelayCreation) != 0)
            {
                DelayCreation = true;
            }
            else
            {
                FinalizeCreation();
            }
        }
Example #8
0
        public static BitmapImage BitmapToBitmapImage(
            ref Bitmap bitmap,
            BitmapCacheOption bmpCacheOption,
            BitmapCreateOptions bmpCreateOptions)
        {
            BitmapImage bi = null;

            try
            {
                //using (var ms = new MemoryStream())
                //{
                var ms = new MemoryStream();
                bitmap.Save(ms, ImageFormat.Bmp);
                ms.Seek(0, SeekOrigin.Begin);

                bi = new BitmapImage();
                bi.BeginInit();
                bi.CreateOptions = bmpCreateOptions;
                bi.CacheOption = bmpCacheOption;
                bi.StreamSource = ms;
                //bi.StreamSource = new MemoryStream(ms.ToArray());
                bi.EndInit();
                bi.Freeze();
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Util.BitmapToBitmapImage has failed.");
                Debug.WriteLine(ex.Message);
            }

            return bi;
        }
Example #9
0
        public static BitmapDecoder Create(
            Stream bitmapStream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption)
        {
            IPlatformBitmapDecoder platformImpl = PlatformInterface.Instance.CreateBitmapDecoder(
                bitmapStream,
                cacheOption);
            BitmapDecoder result;

            switch (platformImpl.ContainerFormat)
            {
                case BitmapContainerFormat.Jpeg:
                    result = new JpegBitmapDecoder(platformImpl);
                    break;
                case BitmapContainerFormat.Png:
                    result = new PngBitmapDecoder(platformImpl);
                    break;
                default:
                    throw new NotSupportedException();
            }

            if (cacheOption == BitmapCacheOption.OnLoad)
            {
                ReadOnlyCollection<BitmapFrame> loadFrames = result.Frames;                
            }

            return result;
        }
Example #10
0
        public static BitmapImage BitmapToBitmapImage(
            ref Bitmap bitmap,
            BitmapCacheOption bmpCacheOption,
            BitmapCreateOptions bmpCreateOptions)
        {
            BitmapImage bi = null;

            try
            {
                //using (var ms = new MemoryStream())
                //{
                var ms = new MemoryStream();
                bitmap.Save(ms, ImageFormat.Bmp);
                ms.Seek(0, SeekOrigin.Begin);

                bi = new BitmapImage();
                bi.BeginInit();
                bi.CreateOptions = bmpCreateOptions;
                bi.CacheOption   = bmpCacheOption;
                bi.StreamSource  = ms;
                //bi.StreamSource = new MemoryStream(ms.ToArray());
                bi.EndInit();
                bi.Freeze();
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Util.BitmapToBitmapImage has failed.");
                Debug.WriteLine(ex.Message);
            }

            return(bi);
        }
Example #11
0
        public static BitmapFrame BitmapToBitmapFrame(
            ref Bitmap bitmap,
            BitmapCacheOption bmpCacheOption,
            BitmapCreateOptions bmpCreateOptions)
        {
            BitmapFrame bf = null;

            try
            {
                using (var ms = new MemoryStream())
                {
                    bitmap.Save(ms, ImageFormat.Bmp);
                    ms.Seek(0, SeekOrigin.Begin);

                    bf = BitmapFrame.Create(new MemoryStream(ms.ToArray()), bmpCreateOptions, bmpCacheOption);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "BitmapToBitmapFrame");
                Debug.WriteLine(ex.Message);
            }

            return bf;
        }
Example #12
0
        public static BitmapFrame BitmapToBitmapFrame(
            ref Bitmap bitmap,
            BitmapCacheOption bmpCacheOption,
            BitmapCreateOptions bmpCreateOptions)
        {
            BitmapFrame bf = null;

            try
            {
                using (var ms = new MemoryStream())
                {
                    bitmap.Save(ms, ImageFormat.Bmp);
                    ms.Seek(0, SeekOrigin.Begin);

                    bf = BitmapFrame.Create(new MemoryStream(ms.ToArray()), bmpCreateOptions, bmpCacheOption);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "BitmapToBitmapFrame");
                Debug.WriteLine(ex.Message);
            }

            return(bf);
        }
Example #13
0
 public BitmapImage(string uriSource, BitmapCacheOption cacheOption = BitmapCacheOption.Default)
 {
     BeginInit();
     this.UriSource = uriSource;
     this.CacheOption = cacheOption;
     EndInit();
 }
 public BmpBitmapDecoder(
     Uri bitmapUri,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     ) : base(bitmapUri, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatBmp)
 {
 }
Example #15
0
        public override IPlatformBitmapDecoder CreateBitmapDecoder(Stream stream, BitmapCacheOption cacheOption)
        {
            DecodeOptions o = (cacheOption == BitmapCacheOption.OnLoad) ?
                              DecodeOptions.CacheOnLoad : DecodeOptions.CacheOnDemand;

            return(new WicBitmapDecoder(this.wicFactory, stream, o));
        }
        /// <summary>
        ///     Creates a BitmapSource from Byte Array.
        /// </summary>
        /// <param name="imageBuffer">The image data.</param>
        /// <param name="decodePixelWidth">Width of the decode pixel. 0 for natural size</param>
        /// <param name="decodePixelHeight">Height of the decode pixel. 0 for natural size</param>
        /// <param name="options">BitmapCacheOption</param>
        /// <returns></returns>
        public static BitmapSource BufferToBitmapSource(byte[] imageBuffer, int decodePixelWidth, int decodePixelHeight,
                                                        BitmapCacheOption options = BitmapCacheOption.Default)
        {
            if (imageBuffer == null)
            {
                return(null);
            }

            var result = new BitmapImage();

            using (var stream = new MemoryStream(imageBuffer))
            {
                result.BeginInit();
                if (decodePixelWidth > 0)
                {
                    result.DecodePixelWidth = decodePixelWidth;
                }
                if (decodePixelHeight > 0)
                {
                    result.DecodePixelHeight = decodePixelHeight;
                }
                result.StreamSource  = stream;
                result.CreateOptions = BitmapCreateOptions.None;
                result.CacheOption   = options;
                result.EndInit();
                if (result.CanFreeze)
                {
                    result.Freeze();
                }
            }

            return(result);
        }
 public PngBitmapDecoder(
     Uri bitmapUri,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     ) : base(bitmapUri, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatPng)
 {
 }
Example #18
0
        public static BitmapDecoder Create(
            Stream bitmapStream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption)
        {
            IPlatformBitmapDecoder platformImpl = PlatformInterface.Instance.CreateBitmapDecoder(
                bitmapStream,
                cacheOption);
            BitmapDecoder result;

            switch (platformImpl.ContainerFormat)
            {
            case BitmapContainerFormat.Jpeg:
                result = new JpegBitmapDecoder(platformImpl);
                break;

            case BitmapContainerFormat.Png:
                result = new PngBitmapDecoder(platformImpl);
                break;

            default:
                throw new NotSupportedException();
            }

            if (cacheOption == BitmapCacheOption.OnLoad)
            {
                ReadOnlyCollection <BitmapFrame> loadFrames = result.Frames;
            }

            return(result);
        }
Example #19
0
 public IconBitmapDecoder(
     Stream bitmapStream,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     ) : base(bitmapStream, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatIco)
 {
 }
 public ImpPngDecoder(Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
     using (var bitmapStream = new FileStream(bitmapUri.LocalPath, FileMode.Open))
     {
         ReadPng(bitmapStream, createOptions, cacheOption);
     }
 }
        // All bitmap laoding eventually invokes this static function
        public static BitmapSource GetBitmapFromImageFile(string filePath, Nullable <int> desiredWidthOrHeight, ImageDisplayIntentEnum displayIntent, ImageDimensionEnum imageDimension, out bool isCorruptOrMissing)
        {
            isCorruptOrMissing = true;

            // BitmapCacheOption.None is significantly faster than other options.
            // However, it locks the file as it is being accessed (rather than a memory copy being created when using a cache)
            // This means we cannot do any file operations on it (such as deleting the currently displayed image) as it will produce an access violation.
            // This is ok for TransientLoading, which just temporarily displays the image
            BitmapCacheOption bitmapCacheOption = (displayIntent == ImageDisplayIntentEnum.Ephemeral) ? BitmapCacheOption.None : BitmapCacheOption.OnLoad;

            if (!System.IO.File.Exists(filePath))
            {
                return(Constant.ImageValues.FileNoLongerAvailable.Value);
            }
            try
            {
                // Exception workarounds to consider: see  http://faithlife.codes/blog/2010/07/exceptions_thrown_by_bitmapimage_and_bitmapframe/
                if (desiredWidthOrHeight.HasValue == false)
                {
                    // returns the full size bitmap
                    BitmapFrame frame = BitmapFrame.Create(new Uri(filePath), BitmapCreateOptions.None, bitmapCacheOption);
                    frame.Freeze();
                    isCorruptOrMissing = false;
                    return(frame);
                }

                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                if (imageDimension == ImageDimensionEnum.UseWidth)
                {
                    bitmap.DecodePixelWidth = desiredWidthOrHeight.Value;
                }
                else
                {
                    bitmap.DecodePixelHeight = desiredWidthOrHeight.Value;
                }
                bitmap.CacheOption = bitmapCacheOption;
                bitmap.UriSource   = new Uri(filePath);
                bitmap.EndInit();
                bitmap.Freeze();

                isCorruptOrMissing = false;
                return(bitmap);
            }
            catch (Exception exception)
            {
                // Optional messages for eventual debugging of catch errors,
                if (exception is InsufficientMemoryException)
                {
                    TracePrint.PrintMessage(String.Format("ImageRow/LoadBitmap: exception getting bitmap from file: {0}\n.** Insufficient Memory Exception: {1}.\n--------------\n**StackTrace: {2}.\nXXXXXXXXXXXXXX\n\n", filePath, exception.Message, exception.StackTrace));
                }
                else
                {
                    // TraceDebug.PrintMessage(String.Format("ImageRow/LoadBitmap: General exception: {0}\n.**Unkonwn exception getting bitmap from file: {1}.\n--------------\n**StackTrace: {2}.\nXXXXXXXXXXXXXX\n\n", filePath, exception.Message, exception.StackTrace));
                }
                isCorruptOrMissing = true;
                return(Constant.ImageValues.Corrupt.Value);
            }
        }
Example #22
0
 public static BitmapSource[] OpenGIF(this BitmapSource source, String fileName,
                                      BitmapCreateOptions create, BitmapCacheOption cache, out BitmapMetadata data)
 {
     using (FileStream stream = new FileStream(fileName, FileMode.Open))
     {
         return(OpenGIF(source, stream, create, cache, out data));
     }
 }
Example #23
0
 public static BitmapSource Load(this BitmapSource source, String fileName, BitmapEncoding enc,
                                 BitmapCreateOptions create, BitmapCacheOption cache, out BitmapMetadata data)
 {
     using (FileStream stream = new FileStream(fileName, FileMode.Open))
     {
         return(Load(source, stream, enc, create, cache, out data));
     }
 }
Example #24
0
        public static BitmapSource[] OpenGIF(this BitmapSource source, Uri uri,
                                             BitmapCreateOptions create, BitmapCacheOption cache, out BitmapMetadata data)
        {
            BitmapDecoder dec = new GifBitmapDecoder(uri, create, cache);

            data = dec.Metadata;
            return(dec.Frames.ToArray());
        }
Example #25
0
 /// <summary>
 /// Create a BitmapFrame from a Uri with the specified BitmapCreateOptions and
 /// BitmapCacheOption
 /// </summary>
 /// <param name="bitmapUri">Uri of the Bitmap</param>
 /// <param name="createOptions">Creation options</param>
 /// <param name="cacheOption">Caching option</param>
 public static BitmapFrame Create(
     Uri bitmapUri,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     )
 {
     return(Create(bitmapUri, createOptions, cacheOption, null));
 }
Example #26
0
        public static BitmapImage GetBitmapImage(Uri imageAbsolutePath, BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
        {
            BitmapImage image = new BitmapImage();

            image.BeginInit();
            image.CacheOption = bitmapCacheOption;
            image.UriSource   = imageAbsolutePath;
            image.EndInit();

            return(image);
        }
Example #27
0
        /// <summary>
        /// 載入指定路徑圖片至記憶體。
        /// </summary>
        /// <param name="pi_sImageFullPath">圖片來源完整路徑。</param>
        /// <param name="pi_nBitmapCacheOption">快取選項。</param>
        /// <param name="pi_nBitmapCreateOption">建構選項。</param>
        /// <returns>圖片物件。</returns>
        /// <remarks>
        /// Author: 黃竣祥
        /// Time: 2017/09/11
        /// History: N/A
        /// DB Object: N/A
        /// </remarks>
        public static BitmapImage LoadBitmapImage(string pi_sImageFullPath, BitmapCacheOption pi_nBitmapCacheOption = BitmapCacheOption.OnLoad, BitmapCreateOptions pi_nBitmapCreateOption = BitmapCreateOptions.IgnoreImageCache)
        {
            BitmapImage objReturn = new BitmapImage();

            objReturn.BeginInit();
            objReturn.UriSource     = new Uri(pi_sImageFullPath);
            objReturn.CacheOption   = BitmapCacheOption.OnLoad;
            objReturn.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            objReturn.EndInit();

            return(objReturn);
        }
        /// <summary>
        /// Load an image from file.
        /// </summary>
        /// <param name="filename">Absolute path to image to load, incl. extension</param>
        /// <returns>Bitmap instance, or null if loading failed</returns>
        public static BitmapSource LoadImageFromFile(string filename)
        {
            if (filename == null)
            {
                return(null);
            }
            if (!File.Exists(filename))
            {
                return(null);
            }

            string ext = Path.GetExtension(filename).ToLower();

            BitmapSource bitmap = null;

            try
            {
                using (Stream in_strm = File.OpenRead(filename))
                {
                    BitmapCreateOptions cr_option = BitmapCreateOptions.PreservePixelFormat;
                    BitmapCacheOption   ca_option = BitmapCacheOption.OnLoad;
                    BitmapDecoder       dec       = null;
                    switch (ext)
                    {
                    case ".bmp":  dec = new BmpBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".gif":  dec = new GifBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".jpeg": dec = new JpegBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".jpg":  dec = new JpegBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".png":  dec = new PngBitmapDecoder(in_strm, cr_option, ca_option); break;

                    case ".tiff": dec = new TiffBitmapDecoder(in_strm, cr_option, ca_option); break;
                    }
                    if (dec == null)
                    {
                        Log.Error("No suitable encoder found for file '{0}'", filename);
                        return(null);
                    }

                    bitmap = dec.Frames[0];
                }
            }
            catch (Exception exc)
            {
                Log.Error("Error loading file '{0}': {1}", filename, exc);
                bitmap = null;
            }

            return(bitmap);
        }
Example #29
0
        public static BitmapImage Create(Stream stream,
                                         BitmapCreateOptions CreateOptions = BitmapCreateOptions.PreservePixelFormat,
                                         BitmapCacheOption CacheOption     = BitmapCacheOption.OnLoad)
        {
            var sourceImg = new BitmapImage();

            sourceImg.BeginInit();
            sourceImg.StreamSource  = stream;
            sourceImg.CacheOption   = CacheOption;
            sourceImg.CreateOptions = CreateOptions;
            sourceImg.EndInit();
            return(sourceImg);
        }
Example #30
0
        private static Freezable LoadImage(Uri uri, BitmapCacheOption bitmapCacheOption)
        {
            var decoder = BitmapDecoder.Create(uri, BitmapCreateOptions.None, bitmapCacheOption); // Лучше эти два параметра не трогать, так как в противном случае в некоторых ситуациях изображения могут перестать отображаться

            if (decoder.Frames.Count == 0)
            {
                return(null);
            }

            var frame = decoder.Frames[0];

            return(frame.CanFreeze ? frame.GetAsFrozen() : frame);
        }
Example #31
0
        public static BitmapImage ToBitmapImage(this Bitmap Bitmap, BitmapCacheOption CacheOption)
        {
            using MemoryStream memory = new MemoryStream(); //Initializes a MemoryStream, which will be disposed of after usage

            Bitmap.Save(memory, ImageFormat.Png);           //Saves the bitmap data to memory
            memory.Position = 0;                            //Moves the pointer back to the beginning to read the data
            BitmapImage bitmapImage = new BitmapImage();    //Initializing our new BitmapImage

            bitmapImage.BeginInit();                        //Sets the new BitmapImage to being able to have properties changed
            bitmapImage.StreamSource = memory;              //Load data from the MemoryStream
            bitmapImage.CacheOption  = CacheOption;         //Set to OnLoad for fastest. Set to OnDemand for lower resource consumption
            bitmapImage.EndInit();                          //Finalises the initialisation for the bitmap image
            return(bitmapImage);
        }
Example #32
0
        /// <summary>
        /// Create BitmapFrame from the uri or stream
        /// </summary>
        internal static BitmapFrame CreateFromUriOrStream(
            Uri baseUri,
            Uri uri,
            Stream stream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            RequestCachePolicy uriCachePolicy
            )
        {
            // Create a decoder and return the first frame
            if (uri != null)
            {
                Debug.Assert((stream == null), "Both stream and uri are non-null");

                BitmapDecoder decoder = BitmapDecoder.CreateFromUriOrStream(
                    baseUri,
                    uri,
                    null,
                    createOptions,
                    cacheOption,
                    uriCachePolicy,
                    true
                    );

                if (decoder.Frames.Count == 0)
                {
                    throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames), "uri");
                }

                return(decoder.Frames[0]);
            }
            else
            {
                Debug.Assert((stream != null), "Both stream and uri are null");

                BitmapDecoder decoder = BitmapDecoder.Create(
                    stream,
                    createOptions,
                    cacheOption
                    );

                if (decoder.Frames.Count == 0)
                {
                    throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames), "stream");
                }

                return(decoder.Frames[0]);
            }
        }
Example #33
0
        /// <summary>
        /// Create BitmapFrame from the uri or stream
        /// </summary>
        internal static BitmapFrame CreateFromUriOrStream(
            Uri baseUri,
            Uri uri,
            Stream stream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            RequestCachePolicy uriCachePolicy
            )
        {
            // Create a decoder and return the first frame
            if (uri != null)
            {
                Debug.Assert((stream == null), "Both stream and uri are non-null");

                BitmapDecoder decoder = BitmapDecoder.CreateFromUriOrStream(
                    baseUri,
                    uri,
                    null,
                    createOptions,
                    cacheOption,
                    uriCachePolicy,
                    true
                    );

                if (decoder.Frames.Count == 0)
                {
                    throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames), "uri");
                }

                return decoder.Frames[0];
            }
            else
            {
                Debug.Assert((stream != null), "Both stream and uri are null");

                BitmapDecoder decoder = BitmapDecoder.Create(
                    stream,
                    createOptions,
                    cacheOption
                    );

                if (decoder.Frames.Count == 0)
                {
                    throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames), "stream");
                }

                return decoder.Frames[0];
            }
        }
 internal UnknownBitmapDecoder(
     SafeMILHandle decoderHandle,
     BitmapDecoder decoder,
     Uri baseUri,
     Uri uri,
     Stream stream,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption,
     bool insertInDecoderCache,
     bool originalWritable,
     Stream uriStream,
     UnmanagedMemoryStream unmanagedMemoryStream,
     SafeFileHandle safeFilehandle             
     ) : base(decoderHandle, decoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, originalWritable, uriStream, unmanagedMemoryStream, safeFilehandle)
 {
 }
Example #35
0
 /// <summary>
 /// Internal Constructor
 /// </summary>
 internal GifBitmapDecoder(
     SafeMILHandle decoderHandle,
     BitmapDecoder decoder,
     Uri baseUri,
     Uri uri,
     Stream stream,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption,
     bool insertInDecoderCache,
     bool originalWritable,
     Stream uriStream,
     UnmanagedMemoryStream unmanagedMemoryStream,
     SafeFileHandle safeFilehandle
     ) : base(decoderHandle, decoder, baseUri, uri, stream, createOptions, cacheOption, insertInDecoderCache, originalWritable, uriStream, unmanagedMemoryStream, safeFilehandle)
 {
 }
        /// <summary>
        /// Construct a CachedBitmap
        /// </summary>
        /// <param name="source">BitmapSource to apply to the crop to</param>
        /// <param name="createOptions">CreateOptions for the new Bitmap</param>
        /// <param name="cacheOption">CacheOption for the new Bitmap</param>
        public CachedBitmap(BitmapSource source, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
            : base(true) // Use base class virtuals
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            BeginInit();
            _source = source;
            RegisterDownloadEventSource(_source);
            _createOptions = createOptions;
            _cacheOption = cacheOption;
            _syncObject = source.SyncObject;

            EndInit();
        }
Example #37
0
        /// <summary>
        /// Construct a CachedBitmap
        /// </summary>
        /// <param name="source">BitmapSource to apply to the crop to</param>
        /// <param name="createOptions">CreateOptions for the new Bitmap</param>
        /// <param name="cacheOption">CacheOption for the new Bitmap</param>
        public CachedBitmap(BitmapSource source, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
            : base(true) // Use base class virtuals
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            BeginInit();
            _source = source;
            RegisterDownloadEventSource(_source);
            _createOptions = createOptions;
            _cacheOption   = cacheOption;
            _syncObject    = source.SyncObject;

            EndInit();
        }
Example #38
0
        /// <summary>
        /// Create a BitmapFrame from a Stream with the specified BitmapCreateOptions and
        /// BitmapCacheOption
        /// </summary>
        /// <param name="bitmapStream">Stream of the Bitmap</param>
        /// <param name="createOptions">Creation options</param>
        /// <param name="cacheOption">Caching option</param>
        public static BitmapFrame Create(
            Stream bitmapStream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption
            )
        {
            if (bitmapStream == null)
            {
                throw new ArgumentNullException("bitmapStream");
            }

            return(CreateFromUriOrStream(
                       null,
                       null,
                       bitmapStream,
                       createOptions,
                       cacheOption,
                       null
                       ));
        }
        private static BitmapImage GetBitmapImage(string previewImage, BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
        {
            var dir      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Domain\Reports\Data");
            var filepath = Path.Combine(dir, previewImage ?? @"missing_template.png");

            if (string.IsNullOrEmpty(previewImage) || !new FileInfo(filepath).Exists)
            {
                filepath = Path.Combine(dir, @"missing_template.png");
            }

            var uri   = new Uri(filepath, UriKind.RelativeOrAbsolute);
            var image = new BitmapImage();

            image.BeginInit();
            image.CacheOption = bitmapCacheOption;
            image.UriSource   = uri;
            image.EndInit();
            image.Freeze();
            return(image);
        }
Example #40
0
        /// <summary>
        /// Create a BitmapFrame from a Uri with the specified BitmapCreateOptions and
        /// BitmapCacheOption
        /// </summary>
        /// <param name="bitmapUri">Uri of the Bitmap</param>
        /// <param name="createOptions">Creation options</param>
        /// <param name="cacheOption">Caching option</param>
        /// <param name="uriCachePolicy">Optional web request cache policy</param>
        public static BitmapFrame Create(
            Uri bitmapUri,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            RequestCachePolicy uriCachePolicy
            )
        {
            if (bitmapUri == null)
            {
                throw new ArgumentNullException("bitmapUri");
            }

            return(CreateFromUriOrStream(
                       null,
                       bitmapUri,
                       null,
                       createOptions,
                       cacheOption,
                       uriCachePolicy
                       ));
        }
Example #41
0
        internal BitmapFrameDecode(
            int frameNumber,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            BitmapFrameDecode frameDecode
            ) : base(true)
        {
            _bitmapInit.BeginInit();
            _frameNumber      = frameNumber;
            WicSourceHandle   = frameDecode.WicSourceHandle;
            IsSourceCached    = frameDecode.IsSourceCached;
            CreationCompleted = frameDecode.CreationCompleted;
            _frameSource      = frameDecode._frameSource;
            _decoder          = frameDecode.Decoder;
            _syncObject       = _decoder.SyncObject;
            _createOptions    = createOptions;
            _cacheOption      = cacheOption;

            _thumbnail             = frameDecode._thumbnail;
            _isThumbnailCached     = frameDecode._isThumbnailCached;
            _metadata              = frameDecode._metadata;
            _isMetadataCached      = frameDecode._isMetadataCached;
            _readOnlycolorContexts = frameDecode._readOnlycolorContexts;
            _isColorContextCached  = frameDecode._isColorContextCached;

            _bitmapInit.EndInit();

            if ((createOptions & BitmapCreateOptions.DelayCreation) != 0)
            {
                DelayCreation = true;
            }
            else if (!CreationCompleted)
            {
                FinalizeCreation();
            }
            else
            {
                UpdateCachedSettings();
            }
        }
        private static BitmapSource Load(object obj, BitmapEncoding enc, 
            BitmapCreateOptions create, BitmapCacheOption cache, out BitmapMetadata data)
        {
            BitmapDecoder dec = null;

            if (obj is Stream)
            {
                Stream stream = obj as Stream;

                switch (enc)
                {
                    case BitmapEncoding.Bmp:
                        dec = new BmpBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Png:
                        dec = new PngBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Jpg:
                        dec = new JpegBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Tiff:
                        dec = new TiffBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Gif:
                        dec = new GifBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Wmp:
                        dec = new WmpBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Icon:
                        dec = new IconBitmapDecoder(stream, create, cache);
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }
            else if (obj is Uri)
            {
                Uri stream = obj as Uri;

                switch (enc)
                {
                    case BitmapEncoding.Bmp:
                        dec = new BmpBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Png:
                        dec = new PngBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Jpg:
                        dec = new JpegBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Tiff:
                        dec = new TiffBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Gif:
                        dec = new GifBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Wmp:
                        dec = new WmpBitmapDecoder(stream, create, cache);
                        break;
                    case BitmapEncoding.Icon:
                        dec = new IconBitmapDecoder(stream, create, cache);
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }
            else
                throw new ArgumentException();

            data = dec.Metadata;
            return dec.Frames[0];
        }
Example #43
0
        internal BitmapFrameDecode( 
            int frameNumber,
            BitmapCreateOptions createOptions, 
            BitmapCacheOption cacheOption,
            LateBoundBitmapDecoder decoder
            ) : base(true)
        { 
            _bitmapInit.BeginInit();
            _frameNumber = frameNumber; 
 
            byte[] pixels = new byte[4];
 
            BitmapSource source = BitmapSource.Create(
                1,
                1,
                96, 
                96,
                PixelFormats.Pbgra32, 
                null, 
                pixels,
                4 
                );

            WicSourceHandle = source.WicSourceHandle;
 
            Debug.Assert(decoder != null);
            _decoder = decoder; 
            _createOptions = createOptions; 
            _cacheOption = cacheOption;
 
            //
            // Hook the decoders download events
            //
            _decoder.DownloadCompleted += OnDownloadCompleted; 
            _decoder.DownloadProgress += OnDownloadProgress;
            _decoder.DownloadFailed += OnDownloadFailed; 
 
            _bitmapInit.EndInit();
        } 
 public BmpBitmapDecoder(Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
 }
 public BmpBitmapDecoder(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
 }
 public static System.Windows.Media.Imaging.BitmapFrame Create(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
   return default(System.Windows.Media.Imaging.BitmapFrame);
 }
        internal BitmapDecoder(
            Stream bitmapStream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            Guid expectedClsId
            )
        {
            Guid clsId = Guid.Empty;
            bool isOriginalWritable = false;

            if (bitmapStream == null)
            {
                throw new ArgumentNullException("bitmapStream");
            }

            _decoderHandle = SetupDecoderFromUriOrStream(
                null,
                bitmapStream,
                cacheOption,
                out clsId,
                out isOriginalWritable,
                out _uriStream,
                out _unmanagedMemoryStream,
                out _safeFilehandle
                );

            if (_uriStream == null)
            {
                GC.SuppressFinalize(this);
            }

            if (clsId != Guid.Empty && clsId != expectedClsId)
            {
                throw new FileFormatException(null, SR.Get(SRID.Image_CantDealWithStream));
            }

            _stream = bitmapStream;
            _createOptions = createOptions;
            _cacheOption = cacheOption;
            _syncObject = _decoderHandle;
            _isOriginalWritable = isOriginalWritable;
            Initialize(null);
        }
Example #48
0
 public JpegBitmapDecoder(Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
     : base(null)
 {
     throw new NotImplementedException();
 }
Example #49
0
 public PngBitmapDecoder(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
     : base(null)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Create a BitmapDecoder from a Uri with the specified BitmapCreateOptions and
        /// BitmapCacheOption
        /// </summary>
        /// <param name="bitmapUri">Uri to decode</param>
        /// <param name="createOptions">Bitmap Create Options</param>
        /// <param name="cacheOption">Bitmap Caching Option</param>
        /// <param name="uriCachePolicy">Optional web request cache policy</param>
        public static BitmapDecoder Create(
            Uri bitmapUri,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            RequestCachePolicy uriCachePolicy
            )
        {
            if (bitmapUri == null)
            {
                throw new ArgumentNullException("bitmapUri");
            }

            return CreateFromUriOrStream(
                null,
                bitmapUri,
                null,
                createOptions,
                cacheOption,
                uriCachePolicy,
                true
                );
        }
        /// <summary>
        /// Create a BitmapDecoder from a Stream with the specified BitmapCreateOptions and
        /// BitmapCacheOption
        /// </summary>
        /// <param name="bitmapStream">Stream to decode</param>
        /// <param name="createOptions">Bitmap Create Options</param>
        /// <param name="cacheOption">Bitmap Caching Option</param>
        public static BitmapDecoder Create(
            Stream bitmapStream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption
            )
        {
            if (bitmapStream == null)
            {
                throw new ArgumentNullException("bitmapStream");
            }

            return CreateFromUriOrStream(
                null,
                null,
                bitmapStream,
                createOptions,
                cacheOption,
                null,
                true
                );
        }
 /// <summary>
 /// Create a BitmapDecoder from a Uri with the specified BitmapCreateOptions and
 /// BitmapCacheOption
 /// </summary>
 /// <param name="bitmapUri">Uri to decode</param>
 /// <param name="createOptions">Bitmap Create Options</param>
 /// <param name="cacheOption">Bitmap Caching Option</param>
 public static BitmapDecoder Create(
     Uri bitmapUri,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     )
 {
     return Create(bitmapUri, createOptions, cacheOption, null);
 }
        internal static BitmapDecoder CreateFromUriOrStream(
            Uri baseUri,
            Uri uri,
            Stream stream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            RequestCachePolicy uriCachePolicy,
            bool insertInDecoderCache
            )
        {
            Guid clsId = Guid.Empty;
            bool isOriginalWritable = false;
            SafeMILHandle decoderHandle = null;
            BitmapDecoder cachedDecoder = null;
            Uri finalUri = null;
            Stream uriStream = null;
            UnmanagedMemoryStream unmanagedMemoryStream = null;
            SafeFileHandle safeFilehandle = null;

            // check to ensure that images are allowed in partial trust
            DemandIfImageBlocked();

            if (uri != null)
            {
                finalUri = (baseUri != null) ?
                               System.Windows.Navigation.BaseUriHelper.GetResolvedUri(baseUri, uri) :
                               uri;

                if (insertInDecoderCache)
                {
                    if ((createOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
                    {
                        ImagingCache.RemoveFromDecoderCache(finalUri);
                    }

                    cachedDecoder = CheckCache(
                        finalUri,
                        out clsId
                        );
                }
            }

            // try to retrieve the cached decoder
            if (cachedDecoder != null)
            {
                decoderHandle = cachedDecoder.InternalDecoder;
            }
            else if ((finalUri != null) && (finalUri.IsAbsoluteUri) && (stream == null) &&
                     ((finalUri.Scheme == Uri.UriSchemeHttp) ||
                      (finalUri.Scheme == Uri.UriSchemeHttps)))
            {
                return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy);
            }
            else if ((stream != null) && (!stream.CanSeek))
            {
                return new LateBoundBitmapDecoder(baseUri, uri, stream, createOptions, cacheOption, uriCachePolicy);
            }
            else
            {
                // Create an unmanaged decoder
                decoderHandle = BitmapDecoder.SetupDecoderFromUriOrStream(
                    finalUri,
                    stream,
                    cacheOption,
                    out clsId,
                    out isOriginalWritable,
                    out uriStream,
                    out unmanagedMemoryStream,
                    out safeFilehandle
                    );
            }

            BitmapDecoder decoder = null;

            // Find out the decoder type and wrap it appropriately and return that
            if (MILGuidData.GUID_ContainerFormatBmp == clsId)
            {
                decoder = new BmpBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatGif == clsId)
            {
                decoder = new GifBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatIco == clsId)
            {
                decoder = new IconBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatJpeg == clsId)
            {
                decoder = new JpegBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatPng == clsId)
            {
                decoder = new PngBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatTiff == clsId)
            {
                decoder = new TiffBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else if (MILGuidData.GUID_ContainerFormatWmp == clsId)
            {
                decoder = new WmpBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }
            else
            {
                decoder = new UnknownBitmapDecoder(
                    decoderHandle,
                    cachedDecoder,
                    baseUri,
                    uri,
                    stream,
                    createOptions,
                    cacheOption,
                    insertInDecoderCache,
                    isOriginalWritable,
                    uriStream,
                    unmanagedMemoryStream,
                    safeFilehandle
                    );
            }

            return decoder;
        }
        internal BitmapDecoder(
            SafeMILHandle decoderHandle,
            BitmapDecoder decoder,
            Uri baseUri,
            Uri uri,
            Stream stream,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            bool insertInDecoderCache,
            bool isOriginalWritable,
            Stream uriStream,
            UnmanagedMemoryStream unmanagedMemoryStream,
            SafeFileHandle safeFilehandle
            )
        {
            _decoderHandle = decoderHandle;
            _baseUri = baseUri;
            _uri = uri;
            _stream = stream;
            _createOptions = createOptions;
            _cacheOption = cacheOption;
            _syncObject = decoderHandle;
            _shouldCacheDecoder = insertInDecoderCache;
            _isOriginalWritable = isOriginalWritable;
            _uriStream = uriStream;
            _unmanagedMemoryStream = unmanagedMemoryStream;
            _safeFilehandle = safeFilehandle;

            if (_uriStream == null)
            {
                GC.SuppressFinalize(this);
            }

            Initialize(decoder);
        }
Example #55
0
        internal BitmapFrameDecode(
            int frameNumber, 
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption, 
            BitmapFrameDecode frameDecode 
            ) : base(true)
        { 
            _bitmapInit.BeginInit();
            _frameNumber = frameNumber;
            WicSourceHandle = frameDecode.WicSourceHandle;
            IsSourceCached = frameDecode.IsSourceCached; 
            CreationCompleted = frameDecode.CreationCompleted;
            _frameSource = frameDecode._frameSource; 
            _decoder = frameDecode.Decoder; 
            _syncObject = _decoder.SyncObject;
            _createOptions = createOptions; 
            _cacheOption = cacheOption;

            _thumbnail = frameDecode._thumbnail;
            _isThumbnailCached = frameDecode._isThumbnailCached; 
            _metadata = frameDecode._metadata;
            _isMetadataCached = frameDecode._isMetadataCached; 
            _readOnlycolorContexts = frameDecode._readOnlycolorContexts; 
            _isColorContextCached = frameDecode._isColorContextCached;
 
            _bitmapInit.EndInit();

            if ((createOptions & BitmapCreateOptions.DelayCreation) != 0)
            { 
                DelayCreation = true;
            } 
            else if (!CreationCompleted) 
            {
                FinalizeCreation(); 
            }
            else
            {
                UpdateCachedSettings(); 
            }
        } 
 public CachedBitmap(BitmapSource source, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
 }
        internal static BitmapSourceSafeMILHandle CreateCachedBitmap(
            BitmapFrame frame,
            BitmapSourceSafeMILHandle wicSource,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            BitmapPalette palette
            )
        {
            BitmapSourceSafeMILHandle wicConverter = null;
            BitmapSourceSafeMILHandle wicConvertedSource = null;

            // For NoCache, return the original
            if (cacheOption == BitmapCacheOption.None)
            {
                return wicSource;
            }

            using (FactoryMaker factoryMaker = new FactoryMaker())
            {
                IntPtr wicFactory = factoryMaker.ImagingFactoryPtr;
                bool changeFormat = false;
                PixelFormat originalFmt = PixelFormats.Pbgra32;

                WICBitmapCreateCacheOptions wicCache = WICBitmapCreateCacheOptions.WICBitmapCacheOnLoad;
                if (cacheOption == BitmapCacheOption.OnDemand)
                {
                    wicCache = WICBitmapCreateCacheOptions.WICBitmapCacheOnDemand;
                }

                originalFmt = PixelFormat.GetPixelFormat(wicSource);
                PixelFormat destFmt = originalFmt;

                // check that we need to change the format of the bitmap
                if (0 == (createOptions & BitmapCreateOptions.PreservePixelFormat))
                {
                    if (!IsCompatibleFormat(originalFmt))
                        changeFormat = true;

                    destFmt = BitmapSource.GetClosestDUCEFormat(originalFmt, palette);
                }

                if (frame != null &&
                    (createOptions & BitmapCreateOptions.IgnoreColorProfile) == 0 &&
                    frame.ColorContexts != null &&
                    frame.ColorContexts[0] != null &&
                    frame.ColorContexts[0].IsValid &&
                    !frame._isColorCorrected &&
                    PixelFormat.GetPixelFormat(wicSource).Format != PixelFormatEnum.Extended
                    )
                {
                    ColorContext destinationColorContext;

                    // We need to make sure, we can actually create the ColorContext for the destination destFmt
                    // If the destFmt is gray or scRGB, the following is not supported, so we cannot
                    // create the ColorConvertedBitmap
                    try
                    {
                        destinationColorContext = new ColorContext(destFmt);
                    }
                    catch (NotSupportedException)
                    {
                        destinationColorContext = null;
                    }

                    if (destinationColorContext != null)
                    {
                        // NOTE: Never do this for a non-MIL pixel format, because the format converter has
                        // special knowledge to deal with the profile

                        bool conversionSuccess = false;
                        bool badColorContext = false;

                        // First try if the color converter can handle the source format directly
                        // Its possible that the color converter does not support certain pixelformats, so put a try/catch here.
                        try
                        {
                            ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap(
                                frame,
                                frame.ColorContexts[0],
                                destinationColorContext,
                                destFmt
                                );

                            wicSource = colorConvertedBitmap.WicSourceHandle;
                            frame._isColorCorrected = true;
                            conversionSuccess = true;
                            changeFormat = false;   // Changeformat no longer necessary, because destFmt already created
                            // by ColorConvertedBitmap
                        }
                        catch (NotSupportedException)
                        {
                        }
                        catch (FileFormatException)
                        {
                            // If the file contains a bad color context, we catch the exception here
                            // and don't bother trying the color conversion below, since color transform isn't possible
                            // with the given color context.
                            badColorContext = true;
                        }

                        if (!conversionSuccess && changeFormat && !badColorContext)
                        {   // If the conversion failed, we first use
                            // a FormatConvertedBitmap, and then Color Convert that one...
                            changeFormat = false;

                            FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(frame, destFmt, null, 0.0);

                            ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap(
                                formatConvertedBitmap,
                                frame.ColorContexts[0],
                                destinationColorContext,
                                destFmt
                                );

                            wicSource = colorConvertedBitmap.WicSourceHandle;
                            frame._isColorCorrected = true;
                            Debug.Assert(destFmt == colorConvertedBitmap.Format);
                            changeFormat = false;   // Changeformat no longer necessary, because destFmt already created
                            // by ColorConvertedBitmap
                        }
                    }
                }

                if (changeFormat)
                {
                    // start up a format converter
                    Guid fmtDestFmt = destFmt.Guid;
                    HRESULT.Check(UnsafeNativeMethods.WICCodec.WICConvertBitmapSource(
                            ref fmtDestFmt,
                            wicSource,
                            out wicConverter));

                    // dump the converted contents into a bitmap
                    HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromSource(
                            wicFactory,
                            wicConverter,
                            wicCache,
                            out wicConvertedSource));
                }
                else
                {
                    // Create the unmanaged resources
                    HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromSource(
                            wicFactory,
                            wicSource,
                            wicCache,
                            out wicConvertedSource));
                }

                wicConvertedSource.CalculateSize();
            }

            return wicConvertedSource;
        }
 public static System.Windows.Media.Imaging.BitmapFrame Create(Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, System.Net.Cache.RequestCachePolicy uriCachePolicy)
 {
   return default(System.Windows.Media.Imaging.BitmapFrame);
 }
        internal BitmapDecoder(
            Uri bitmapUri,
            BitmapCreateOptions createOptions,
            BitmapCacheOption cacheOption,
            Guid expectedClsId
            )
        {
            Guid clsId = Guid.Empty;
            bool isOriginalWritable = false;

            if (bitmapUri == null)
            {
                throw new ArgumentNullException("bitmapUri");
            }

            if ((createOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
            {
                ImagingCache.RemoveFromDecoderCache(bitmapUri);
            }

            BitmapDecoder decoder = CheckCache(bitmapUri, out clsId);
            if (decoder != null)
            {
                _decoderHandle = decoder.InternalDecoder;
            }
            else
            {
                _decoderHandle = SetupDecoderFromUriOrStream(
                    bitmapUri,
                    null,
                    cacheOption,
                    out clsId,
                    out isOriginalWritable,
                    out _uriStream,
                    out _unmanagedMemoryStream,
                    out _safeFilehandle
                    );

                if (_uriStream == null)
                {
                    GC.SuppressFinalize(this);
                }
            }

            if (clsId != expectedClsId)
            {
                throw new FileFormatException(bitmapUri, SR.Get(SRID.Image_CantDealWithUri));
            }

            _uri = bitmapUri;
            _createOptions = createOptions;
            _cacheOption = cacheOption;
            _syncObject = _decoderHandle;
            _isOriginalWritable = isOriginalWritable;
            Initialize(decoder);
        }
        internal static SafeMILHandle SetupDecoderFromUriOrStream(
            Uri uri,
            Stream stream,
            BitmapCacheOption cacheOption,
            out Guid clsId,
            out bool isOriginalWritable,
            out Stream uriStream,
            out UnmanagedMemoryStream unmanagedMemoryStream,
            out SafeFileHandle safeFilehandle
            )
        {
            SafeMILHandle decoderHandle;
            IntPtr decoder = IntPtr.Zero;
            System.IO.Stream bitmapStream = null;
            string mimeType = String.Empty;
            // check to ensure that images are allowed in partial trust NOP in full trust
            DemandIfImageBlocked();
            unmanagedMemoryStream = null;
            safeFilehandle = null;
            isOriginalWritable = false;
            uriStream = null;

            if ((uri != null) && (stream != null))
            {
                // In this case we expect the Uri to be http(s)
                Debug.Assert((uri.Scheme == Uri.UriSchemeHttp) || (uri.Scheme == Uri.UriSchemeHttps));
                Debug.Assert(stream.CanSeek);
            }

            // Uri
            if (uri != null)
            {
                if (uri.IsAbsoluteUri)
                {
                    // In this case we first check to see if the consumer has media permissions for
                    // safe media (Site of Origin + Cross domain)
                    SecurityHelper.DemandMediaPermission(MediaPermissionAudio.NoAudio,
                                                         MediaPermissionVideo.NoVideo,
                                                         MediaPermissionImage.SiteOfOriginImage) ;
                    // This code path executes only for pack web requests
                    if (String.Compare(uri.Scheme, PackUriHelper.UriSchemePack, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        WebResponse response = WpfWebRequestHelper.CreateRequestAndGetResponse(uri);
                        mimeType = response.ContentType;
                        bitmapStream = response.GetResponseStream();
                        uriStream = bitmapStream;
                    }
                }

                if ((bitmapStream == null) || (bitmapStream == System.IO.Stream.Null))
                {
                    // We didn't get a stream from the pack web request, so we have
                    // to try to create one ourselves.
                    if (uri.IsAbsoluteUri)
                    {
                        // The Uri class can't tell if it is a file unless it
                        // has an absolute path.
                        int targetZone = SecurityHelper.MapUrlToZoneWrapper(uri);
                        if (targetZone == MS.Win32.NativeMethods.URLZONE_LOCAL_MACHINE)
                        {
                            if (uri.IsFile)
                            {
                                // FileStream does a demand for us, so no need to do a demand
                                bitmapStream = new System.IO.FileStream(uri.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                            }
                        }
                        else // Any other zone
                        {
                            // UNC path for a file which is not http
                            if (uri.IsFile && uri.IsUnc) // for UNC
                            {
                                bitmapStream = ProcessUncFiles(uri);
                            }
                            else if (uri.Scheme == Uri.UriSchemeHttp) // for http
                            {
                                bitmapStream = ProcessHttpFiles(uri,stream);
                            }
                            else if (uri.Scheme == Uri.UriSchemeHttps) // for https
                            {
                                bitmapStream = ProcessHttpsFiles(uri,stream);
                            }
                            else
                            {
                                // The Uri is a custom Uri. Try to grab the stream from its WebResponse.
                                bitmapStream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(uri);
                            }
                        }
                    }
                    else
                    {
                        #pragma warning disable 6518
                        // We don't have an absolute URI, so we don't necessarily know
                        // if it is a file, but we'll have to assume it is and try to
                        // create a stream from the original string.
                        bitmapStream = new System.IO.FileStream(uri.OriginalString, FileMode.Open, FileAccess.Read, FileShare.Read);
                        #pragma warning restore 6518
                    }

                    uriStream = bitmapStream;
                }
            }

            // We need to use the stream created from the Uri.
            if (bitmapStream != null)
            {
                stream = bitmapStream;
            }
            else
            {
                // Note whether the original stream is writable.
                isOriginalWritable = stream.CanSeek && stream.CanWrite;
            }

            // Make sure we always use a seekable stream to avoid problems with http Uris etc.
            stream = GetSeekableStream(stream);

            if (stream is UnmanagedMemoryStream)
            {
                unmanagedMemoryStream = stream as UnmanagedMemoryStream;
            }

            IntPtr comStream = IntPtr.Zero;

            if (stream is System.IO.FileStream)
            {
                System.IO.FileStream filestream = stream as System.IO.FileStream;

                try
                {
                    safeFilehandle = filestream.SafeFileHandle;
                }
                catch
                {
                    // If Filestream doesn't support SafeHandle then revert to old code path.
                    safeFilehandle = null;
                }
            }

            try
            {
                Guid vendorMicrosoft = new Guid(MILGuidData.GUID_VendorMicrosoft);
                UInt32 metadataFlags = (uint)WICMetadataCacheOptions.WICMetadataCacheOnDemand;

                if (cacheOption == BitmapCacheOption.OnLoad)
                {
                    metadataFlags = (uint)WICMetadataCacheOptions.WICMetadataCacheOnLoad;
                }

                // We have a SafeHandle.
                if (safeFilehandle != null)
                {
                    using (FactoryMaker myFactory = new FactoryMaker())
                    {
                        HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateDecoderFromFileHandle(
                            myFactory.ImagingFactoryPtr,
                            safeFilehandle,
                            ref vendorMicrosoft,
                            metadataFlags,
                            out decoder
                            ));
                    }
                }
                else
                {
                    comStream = BitmapDecoder.GetIStreamFromStream(ref stream);

                    using (FactoryMaker myFactory = new FactoryMaker())
                    {

                        // This does an add-ref on the comStream
                        HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateDecoderFromStream(
                            myFactory.ImagingFactoryPtr,
                            comStream,
                            ref vendorMicrosoft,
                            metadataFlags,
                            out decoder
                            ));
                    }
                }
                Debug.Assert(decoder != IntPtr.Zero);
                decoderHandle = new SafeMILHandle(decoder);
            }
            catch
            {
                #pragma warning disable 6500

                decoderHandle = null;
                throw;

                #pragma warning restore 6500
            }
            finally
            {
                UnsafeNativeMethods.MILUnknown.ReleaseInterface(ref comStream);
            }

            string decoderMimeTypes;
            clsId = GetCLSIDFromDecoder(decoderHandle, out decoderMimeTypes);

            // If the mime type of the file does not match the associated decoder,
            // and if we are in a Partial trust scenario, throw!
            if ((mimeType != String.Empty) &&
                (decoderMimeTypes.IndexOf(mimeType, StringComparison.OrdinalIgnoreCase) == -1))
            {
                try
                {
                    SecurityHelper.DemandUnmanagedCode();
                }
                catch(SecurityException)
                {
                    throw new ArgumentException(SR.Get(SRID.Image_ContentTypeDoesNotMatchDecoder));
                }
            }

            return decoderHandle;
        }