示例#1
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));
        }
示例#2
0
        private static BitmapDecoder GetDecoder(BitmapSource image, out GifFile gifFile)
        {
            gifFile = null;
            BitmapDecoder       decoder      = null;
            Stream              bitmapStream = null;
            Uri                 result       = null;
            BitmapCreateOptions none         = BitmapCreateOptions.None;
            BitmapImage         image2       = image as BitmapImage;

            if (image2 == null)
            {
                BitmapFrame frame = image as BitmapFrame;
                if (frame != null)
                {
                    decoder = frame.Decoder;
                    Uri.TryCreate(frame.BaseUri, frame.ToString(), out result);
                }
            }
            else
            {
                none = image2.CreateOptions;
                if (image2.StreamSource != null)
                {
                    bitmapStream = image2.StreamSource;
                }
                else if (image2.UriSource != null)
                {
                    result = image2.UriSource;
                    if ((image2.BaseUri != null) && !result.IsAbsoluteUri)
                    {
                        result = new Uri(image2.BaseUri, result);
                    }
                }
            }
            if (decoder == null)
            {
                if (bitmapStream != null)
                {
                    bitmapStream.Position = 0L;
                    decoder = BitmapDecoder.Create(bitmapStream, none, BitmapCacheOption.OnLoad);
                }
                else if ((result != null) && result.IsAbsoluteUri)
                {
                    decoder = BitmapDecoder.Create(result, none, BitmapCacheOption.OnLoad);
                }
            }
            if ((decoder is GifBitmapDecoder) && !CanReadNativeMetadata(decoder))
            {
                if (bitmapStream != null)
                {
                    bitmapStream.Position = 0L;
                    gifFile = GifFile.ReadGifFile(bitmapStream, true);
                }
                else if (result != null)
                {
                    gifFile = DecodeGifFile(result);
                }
            }
            return(decoder);
        }
 public BmpBitmapDecoder(
     Uri bitmapUri,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     ) : base(bitmapUri, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatBmp)
 {
 }
示例#4
0
 public IconBitmapDecoder(
     Stream bitmapStream,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     ) : base(bitmapStream, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatIco)
 {
 }
 public PngBitmapDecoder(
     Uri bitmapUri,
     BitmapCreateOptions createOptions,
     BitmapCacheOption cacheOption
     ) : base(bitmapUri, createOptions, cacheOption, MILGuidData.GUID_ContainerFormatPng)
 {
 }
示例#6
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;
            }
        }
示例#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(); 
            }
        }
示例#8
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();
            }
        }
示例#9
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);
        }
示例#10
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)
 {
 }
示例#11
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);
        }
示例#12
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;
        }
示例#13
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;
        }
示例#14
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;
        }
示例#15
0
    public bool setGPS(GPSInfo theGPS) {

      double latitude = theGPS.Latitude;
      double longitude = theGPS.Longitude;
      double altitude = theGPS.Altitude;

      //original image file
      string originalPath = _InputFileName;
      //image file after adding the GPS tags
      string outputPath = _OutputFileName;

      BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;
      uint paddingAmount = 2048;

      //open the image file
      using (Stream originalFile = File.Open(originalPath, FileMode.Open, FileAccess.Read)) {
        BitmapDecoder original = BitmapDecoder.Create(originalFile, createOptions, BitmapCacheOption.None);

        //this becomes the new image that contains new metadata
        JpegBitmapEncoder output = new JpegBitmapEncoder();

        if (original.Frames[0] != null && original.Frames[0].Metadata != null) {
          //clone the metadata from the original input image so that it can be modified
          BitmapMetadata metadata = original.Frames[0].Metadata.Clone() as BitmapMetadata;

          //pad the metadata so that it can be expanded with new tags
          metadata.SetQuery("/app1/ifd/PaddingSchema:Padding", paddingAmount);
          metadata.SetQuery("/app1/ifd/exif/PaddingSchema:Padding", paddingAmount);
          metadata.SetQuery("/xmp/PaddingSchema:Padding", paddingAmount);


          GPSRational latitudeRational = new GPSRational(latitude);
          GPSRational longitudeRational = new GPSRational(longitude);
          metadata.SetQuery(GPSLatitudeQuery, latitudeRational.bytes);
          metadata.SetQuery(GPSLongitudeQuery, longitudeRational.bytes);
          if (latitude > 0) metadata.SetQuery(GPSLatitudeRefQuery, "N");
          else metadata.SetQuery(GPSLatitudeRefQuery, "S");
          if (longitude > 0) metadata.SetQuery(GPSLongitudeRefQuery, "E");
          else metadata.SetQuery(GPSLongitudeRefQuery, "W");

          //denoninator = 1 for Rational
          Rational altitudeRational = new Rational((int)altitude, 1);
          metadata.SetQuery(GPSAltitudeQuery, altitudeRational.bytes);

          //create the output image using the image data, thumbnail, and metadata from the original image as modified above
          output.Frames.Add(
              BitmapFrame.Create(original.Frames[0], original.Frames[0].Thumbnail, metadata, original.Frames[0].ColorContexts));
        }//if (original.Frames[0] != null)

        //save the output image
        using (Stream outputFile = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite)) {
          output.Save(outputFile);
        }//using (Stream outputFile)

        //Delete the source file
        //System.IO.File.Delete(originalPath);
      }//using (Stream originalFile)

      return true;
    }//public bool GPS)
示例#16
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);
        }
 public ImpPngDecoder(Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
     using (var bitmapStream = new FileStream(bitmapUri.LocalPath, FileMode.Open))
     {
         ReadPng(bitmapStream, createOptions, cacheOption);
     }
 }
        /// <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;
                }
            }
        }
示例#19
0
        private void CreateOptionsPropertyChangedHook(DependencyPropertyChangedEventArgs e)
        {
            BitmapCreateOptions options = (BitmapCreateOptions)e.NewValue;

            _createOptions = options;
            DelayCreation  = ((options & BitmapCreateOptions.DelayCreation) != 0);
        }
示例#20
0
 public ImageProvider(Uri imageUri,
                      int decodePixelWidth,
                      BitmapCreateOptions bitmapCreateOptions = BitmapCreateOptions.IgnoreColorProfile)
 {
     ImageUri            = imageUri;
     DecodePixelWidth    = decodePixelWidth;
     BitmapCreateOptions = bitmapCreateOptions;
 }
示例#21
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));
 }
示例#22
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());
        }
示例#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));
     }
 }
示例#24
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));
     }
 }
        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);
        }
		public static BitmapImage ByteArray2Bitmap(byte[] bitData, BitmapCreateOptions option = BitmapCreateOptions.BackgroundCreation)
		{
			BitmapImage bitmap = new BitmapImage();
			using (MemoryStream ms = new MemoryStream(bitData))
			{
				bitmap.CreateOptions = option;
				bitmap.SetSource(ms);
				return bitmap;
			}
		}
        public static BitmapImage ByteArray2Bitmap(byte[] bitData, BitmapCreateOptions option = BitmapCreateOptions.BackgroundCreation)
        {
            BitmapImage bitmap = new BitmapImage();

            using (MemoryStream ms = new MemoryStream(bitData))
            {
                bitmap.CreateOptions = option;
                bitmap.SetSource(ms);
                return(bitmap);
            }
        }
        /// <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);
        }
示例#29
0
 public void SetImageCreateOptions(BitmapCreateOptions createOptions)
 {
     if (ElementIcon != null && ElementIcon.Source != null)
     {
         _createOptions = createOptions;
         ((BitmapImage)ElementIcon.Source).CreateOptions = createOptions;
     }
     else
     {
         _createOptions = createOptions;
     }
 }
示例#30
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);
        }
示例#31
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]);
            }
        }
示例#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];
            }
        }
示例#33
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)
 {
 }
 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)
 {
 }
        /// <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();
        }
示例#36
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();
        }
示例#37
0
        public static BitmapImage CreateImage(Stream stream, BitmapCreateOptions options)
        {
            BitmapImage imageSource;

            try
            {
                stream.Seek(0, SeekOrigin.Begin);
                var image = new BitmapImage();
                image.CreateOptions = options;
                image.SetSource(stream);
                imageSource = image;
            }
            catch (Exception)
            {
                return(null);
            }

            return(imageSource);
        }
示例#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
                       ));
        }
示例#39
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
                       ));
        }
示例#40
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();
            }
        }
示例#41
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();
        }
示例#42
0
        public static BitmapImage CreateImage(byte[] buffer, BitmapCreateOptions options)
        {
            BitmapImage imageSource;

            try
            {
                using (var stream = new MemoryStream(buffer))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    var image = new BitmapImage();
                    image.CreateOptions = options;
                    image.SetSource(stream);
                    imageSource = image;
                }
            }
            catch (Exception)
            {
                return(null);
            }

            return(imageSource);
        }
示例#43
0
    public static BitmapImage LoadBitmapFromResource(string path,
      BitmapCreateOptions options)
    {
      var stminfo = Application.GetResourceStream(new Uri(path, UriKind.Relative));
      if (null == stminfo
        || null == stminfo.Stream)
        return null;

      using (var stm = stminfo.Stream)
      {
        var bmp = new BitmapImage
        {
          CreateOptions = options
        };
        bmp.SetSource(stm);
        return bmp;
      }

    }
示例#44
0
    public static BitmapImage LoadBitmapFromIso(string path,
      BitmapCreateOptions options)
    {
      byte[] raw = StorageIo.ReadBinaryFile(path);
      if (null == raw)
        return null;

      using (var stm = new MemoryStream())
      {
        stm.Write(raw, 0, raw.Length);
        stm.Seek(0, SeekOrigin.Begin);

        var img = new BitmapImage
        {
          CreateOptions = options
        };

        img.SetSource(stm);
        return img;
      }
    }
示例#45
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(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
 }
        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;
        }
示例#48
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(); 
            }
        } 
示例#49
0
 public JpegBitmapDecoder(Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
     : base(null)
 {
     throw new NotImplementedException();
 }
 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);
 }
 public static System.Windows.Media.Imaging.BitmapFrame Create(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
   return default(System.Windows.Media.Imaging.BitmapFrame);
 }
        /// <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
                );
        }
 public BmpBitmapDecoder(Uri bitmapUri, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
 {
 }
        /// <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);
 }
示例#56
0
 public PngBitmapDecoder(Stream bitmapStream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption)
     : base(null)
 {
     throw new NotImplementedException();
 }
        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;
        }
        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);
        }
        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);
        }
示例#60
0
    /// <summary>
    /// Get bitmap from resource
    /// </summary>
    /// <param name="assemblyName"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public static BitmapSource BitmapFromResource(
            string assemblyName,
            string path,
            BitmapCreateOptions option)
    {
      string pathToResource =
                string.Format("/{0};component{1}",
                              assemblyName,
                              path);
      if (Pool.ContainsKey(pathToResource))
        return Pool[pathToResource];

      BitmapImage img =
                new BitmapImage(new Uri(pathToResource, UriKind.Relative));
      img.CreateOptions = option;
      return img;
    }