コード例 #1
0
        /// <summary>
        /// Async loading image from cache or network
        /// </summary>
        /// <param name="imageUri">Uri of the image to load</param>
        /// <returns>BitmapImage if load was successfull or null otherwise</returns>
        public virtual async Task <ImagePackage> LoadImage(Image image, Uri uriSource,
                                                           CancellationTokenSource cancellationTokenSource)
        {
            CheckConfig();
            ImagePackage imagePackage = null;
            var          decoders     = this.GetAvailableDecoders();

            var randStream = await this.LoadImageStream(uriSource, cancellationTokenSource);

            if (randStream == null)
            {
                throw new Exception("stream is null");
            }
            if (decoders.Count > 0)
            {
                int maxHeaderSize = decoders.Max(x => x.HeaderSize);
                if (maxHeaderSize > 0)
                {
                    byte[] header     = new byte[maxHeaderSize];
                    var    readStream = randStream.AsStreamForRead();
                    readStream.Position = 0;
                    await readStream.ReadAsync(header, 0, maxHeaderSize);

                    readStream.Position = 0;
                    int           maxPriority = -1;
                    IImageDecoder decoder     = null;
                    foreach (var item in decoders)
                    {
                        var priority = item.GetPriority(header);
                        if (priority > maxPriority)
                        {
                            maxPriority = priority;
                            decoder     = item;
                        }
                    }
                    if (decoder != null)
                    {
                        var package = await decoder.InitializeAsync(image.Dispatcher, image, uriSource, randStream, cancellationTokenSource);

                        if (!cancellationTokenSource.IsCancellationRequested)
                        {
                            imagePackage = package;
                            //imagePackage?.Decoder?.Start();
                        }
                    }
                }
            }
            return(imagePackage);

            //var bitmapImage = new BitmapImage();
            //var stream = await LoadImageStream(imageUri, cancellationTokenSource);
            //await bitmapImage.SetSourceAsync(stream);
            //return bitmapImage;
        }