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

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

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

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

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

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

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

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

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

                default:
                    return bitmap;
            }
        }
        public void Shrink(string sourcePath)
        {
            Debug.Assert(!String.IsNullOrWhiteSpace(sourcePath));

            BitmapDecoder decoder;
            BitmapEncoder encoder;
            GetBitmapDecoderEncoder(sourcePath, out decoder, out encoder);
            if (decoder == null || encoder == null)
                throw new ArgumentException("Image type is not supported.");

            // NOTE: grab its first (and usually only) frame. Only TIFF and GIF images support multiple frames
            var sourceFrame = decoder.Frames[0];

            // Apply the transform
            var transform = GetTransform(sourceFrame);

            if (transform == null)
                return;

            var transformedBitmap = new TransformedBitmap(sourceFrame, transform);

            // Create the destination frame
            var thumbnail = sourceFrame.Thumbnail;
            var metadata = sourceFrame.Metadata as BitmapMetadata;
            var colorContexts = sourceFrame.ColorContexts;
            var destinationFrame = BitmapFrame.Create(transformedBitmap, thumbnail, metadata, colorContexts);

            encoder.Frames.Add(destinationFrame);

            SaveResultToFile(sourcePath, encoder);
        }
        /// <summary>
        ///     Resizes the image presented by the <paramref name="imageData"/> to a <paramref name="newSize"/>.
        /// </summary>
        /// <param name="imageData">
        ///     The binary data of the image to resize.
        /// </param>
        /// <param name="newSize">
        ///     The size to which to resize the image.
        /// </param>
        /// <param name="keepAspectRatio">
        ///     A flag indicating whether to save original aspect ratio.
        /// </param>
        /// <returns>
        ///     The structure which contains binary data of resized image and the actial size of resized image depending on <paramref name="keepAspectRatio"/> value.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        ///     An error occurred during resizing the image.
        /// </exception>
        public static Task<ImageInfo> ResizeAsync(this byte[] imageData, Size newSize, bool keepAspectRatio)
        {
            var result = new ImageInfo();
            var image = imageData.ToBitmap();
            var percentWidth = (double) newSize.Width/(double) image.PixelWidth;
            var percentHeight = (double) newSize.Height/(double) image.PixelHeight;

            ScaleTransform transform;
            if (keepAspectRatio)
            {
                transform = percentWidth < percentHeight
                                ? new ScaleTransform {ScaleX = percentWidth, ScaleY = percentWidth}
                                : new ScaleTransform {ScaleX = percentHeight, ScaleY = percentHeight};
            }
            else
            {
                transform = new ScaleTransform {ScaleX = percentWidth, ScaleY = percentHeight};
            }

            var resizedImage = new TransformedBitmap(image, transform);

            using (var memoryStream = new MemoryStream())
            {
                var jpegEncoder = new JpegBitmapEncoder();
                jpegEncoder.Frames.Add(BitmapFrame.Create(resizedImage));
                jpegEncoder.Save(memoryStream);

                result.Data = memoryStream.ToArray();
                result.Size = new Size(resizedImage.PixelWidth, resizedImage.PixelHeight);
            }

            return Task.FromResult(result);
        }
        public bool TryGetBitmapTransform(string optionValue, IEnumerable<KeyValuePair<string, string>> settings, out Func<BitmapSource, BitmapSource> bitmapTransformerFunc)
        {
            var cropOriginFunc = GetCropPointFunc(GetSetting(settings, "cropOrigin", "center,center"));
            var cropSize = GetCropSize(optionValue);

            bitmapTransformerFunc = bitmapSource =>
            {
                double widthScale = cropSize.Width / bitmapSource.PixelWidth;
                double heightScale = cropSize.Height / bitmapSource.PixelHeight;
                double scale = Math.Max(widthScale, heightScale);

                bitmapSource = new TransformedBitmap(bitmapSource, new ScaleTransform(scale, scale));

                var cropOrigin = cropOriginFunc(bitmapSource);
                var x = cropOrigin.X - (cropSize.Width / 2);
                x = Math.Max(0, x);
                x = Math.Min(x, bitmapSource.PixelWidth - cropSize.Width);

                var y = cropOrigin.Y - (cropSize.Height / 2);
                y = Math.Max(0, y);
                y = Math.Min(y, bitmapSource.PixelHeight - cropSize.Height);

                return new CroppedBitmap(bitmapSource, new Int32Rect((int)Math.Round(x), (int)Math.Round(y), (int)cropSize.Width, (int)cropSize.Height));
            };

            return true;
        }
      public void PageLoaded(object sender, RoutedEventArgs args)
      {
         // Create Image element.
         Image rotated90 = new Image();
         rotated90.Width = 150;

         // Create the TransformedBitmap to use as the Image source.
         TransformedBitmap tb = new TransformedBitmap();

         // Create the source to use as the tb source.
         BitmapImage bi = new BitmapImage();
         bi.BeginInit();
         bi.UriSource = new Uri(@"sampleImages/watermelon.jpg", UriKind.RelativeOrAbsolute);
         bi.EndInit();

         // Properties must be set between BeginInit and EndInit calls.
         tb.BeginInit();
         tb.Source = bi;
         // Set image rotation.
         RotateTransform transform = new RotateTransform(90);
         tb.Transform = transform;
         tb.EndInit();
         // Set the Image source.
         rotated90.Source = tb;

         //Add Image to the UI
         Grid.SetColumn(rotated90, 1);
         Grid.SetRow(rotated90, 1);
         transformedGrid.Children.Add(rotated90);

      }
        public static void DrawImage (this ConsoleBuffer @this, ImageSource imageSource, int x, int y, int width, int height)
        {
            var bmp = imageSource as BitmapSource;
            if (bmp == null)
                throw new ArgumentException("Only rendering of bitmap source is supported.");

            @this.OffsetX(ref x).OffsetY(ref y);
            int x1 = x, x2 = x + width, y1 = y, y2 = y + height;
            if ([email protected](ref x1, ref y1, ref x2, ref y2))
                return;

            if (width != bmp.PixelWidth || height != bmp.PixelHeight)
                bmp = new TransformedBitmap(bmp, new ScaleTransform((double)width / bmp.PixelWidth, (double)height / bmp.PixelHeight));
            if (bmp.Format != PixelFormats.Indexed4)
                bmp = new FormatConvertedBitmap(bmp, PixelFormats.Indexed4, BitmapPalettes.Halftone8Transparent, 0.5);

            const int bitsPerPixel = 4;
            int stride = 4 * (bmp.PixelWidth * bitsPerPixel + 31) / 32;
            byte[] bytes = new byte[stride * bmp.PixelHeight];
            bmp.CopyPixels(bytes, stride, 0);

            for (int iy = y1, py = 0; iy < y2; iy++, py++) {
                ConsoleChar[] charsLine = @this.GetLine(iy);
                for (int ix = x1, px = 0; ix < x2; ix++, px++) {
                    int byteIndex = stride * py + px / 2;
                    int bitOffset = px % 2 == 0 ? 4 : 0;
                    SetColor(ref charsLine[ix], bmp.Palette, (bytes[byteIndex] >> bitOffset) & 0xF);
                }
            }
        }
 private TransformedBitmap GetTransformedBitmapFromUri(string uri)
 {
     var bitmap = new Bitmap(uri);
     var requiredRotation = GetRotationFromImage(bitmap);
     var bitmapImage = new BitmapImage(new Uri(uri));
     var transform = new RotateTransform(requiredRotation);
     var tb = new TransformedBitmap(bitmapImage, transform);
     return tb;
 }
        private static byte[] ResizeImage(ImageFormat format, BitmapSource photo, double? width, double? height)
        {
            var scaleX = (width.GetValueOrDefault(photo.Width) / photo.Width);
            var scaleY = (height.GetValueOrDefault(photo.Height) / photo.Height);

            var target = new TransformedBitmap(photo, new ScaleTransform(scaleX, scaleY, 0, 0));

            var targetFrame = BitmapFrame.Create(target);
            return targetFrame.ToByteArray(format);
        }
Example #9
0
        private void buttonRotate_Click(object sender, RoutedEventArgs e)
        {
            TransformedBitmap tb = new TransformedBitmap();
            tb.BeginInit();
            tb.Transform = new RotateTransform(90);
            tb.Source = this.imageViewModel.LoadedBitmap;
            tb.EndInit();
            this.imageViewModel.LoadedBitmap = tb;

            this.imageViewModel.ClearPositions();
        }
Example #10
0
        /// <summary>
        /// Converts a bitmap and returns the result.
        /// </summary>
        /// <param name="bitmap">The bitmap to convert.</param>
        /// <returns>The result.</returns>
        public BitmapSource Convert(BitmapSource bitmap)
        {
            BitmapSource result = bitmap;

            if(bitmap.Format != _format)
                result = new FormatConvertedBitmap(result, _format, null, 0);

            if(Rotate != 0)
                result = new TransformedBitmap(result, new RotateTransform(Rotate));

            return result;
        }
Example #11
0
 public static void TransformSave(BitmapSource bi, double scale, int quality, string filename)
 {
     var tr = new ScaleTransform(scale, scale);
     TransformedBitmap tb = new TransformedBitmap(bi, tr);
     //if (File.Exists(filename)) File.Delete(filename);
     var stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
     JpegBitmapEncoder encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
     encoder.QualityLevel = quality;
     encoder.Frames.Add(BitmapFrame.Create(tb));
     encoder.Save(stream);
     stream.Close();
 }
        public ShowMyFace()
        {
            Title = "Show My Face";

            ///******************************************************************
            //  3���� ShowMyFace ����
            //******************************************************************/
            Uri uri = new Uri("http://www.charlespetzold.com/PetzoldTattoo.jpg");
            //BitmapImage bitmap = new BitmapImage(uri);
            //Image img = new Image();
            //img.Source = bitmap;
            //Content = img;

            ///******************************************************************
            //  p1245 BitmapImage �ڵ�
            //******************************************************************/
            Image rotated90 = new Image();
            TransformedBitmap tb = new TransformedBitmap();
            FormatConvertedBitmap fb = new FormatConvertedBitmap();
            CroppedBitmap cb = new CroppedBitmap();

            // Create the source to use as the tb source.
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = uri;
            bi.EndInit();

            //cb.BeginInit();
            //cb.Source = bi;
            //Int32Rect rect = new Int32Rect();
            //rect.X = 220;
            //rect.Y = 200;
            //rect.Width = 120;
            //rect.Height = 80;
            //cb.SourceRect = rect;

            //cb.EndInit();

            fb.BeginInit();
            fb.Source = bi;
            fb.DestinationFormat = PixelFormats.Gray2;
            fb.EndInit();

            // Properties must be set between BeginInit and EndInit calls.
            tb.BeginInit();
            tb.Source = fb;
            // Set image rotation.
            tb.Transform = new RotateTransform(90);
            tb.EndInit();
            // Set the Image source.
            rotated90.Source = tb;
            Content = rotated90;
        }
        /// <summary>
        /// Resizes the given Image
        /// </summary>
        /// <param name="source"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static BitmapImage ResizeImage(BitmapImage source, int width, int height)
        {
            var target = new TransformedBitmap(
                            source,
                            new ScaleTransform(
                                width / source.Width * 96 / source.DpiX,
                                height / source.Height * 96 / source.DpiY,
                                0, 0));

            var resizedFrame = BitmapFrame.Create(target);

            return FrameToBitmap(resizedFrame);
        }
Example #14
0
        public async Task EncodeColorAsync(byte[] colorData, BinaryWriter writer)
        {
            await Task.Run(() =>
            {
                var format = PixelFormats.Bgra32;
                int stride = (int)this.Width * format.BitsPerPixel / 8;
                var bmp = BitmapSource.Create(
                    this.Width,
                    this.Height,
                    96.0,
                    96.0,
                    format,
                    null,
                    colorData,
                    stride);
                BitmapFrame frame;
                if (this.Width != this.OutputWidth || this.Height != this.OutputHeight)
                {
                    var transform = new ScaleTransform((double)this.OutputHeight / this.Height, (double)this.OutputHeight / this.Height);
                    var scaledbmp = new TransformedBitmap(bmp, transform);
                    frame = BitmapFrame.Create(scaledbmp);
                }
                else
                {
                    frame = BitmapFrame.Create(bmp);
                }

                var encoder = new JpegBitmapEncoder()
                {
                    QualityLevel = this.JpegQuality
                };
                encoder.Frames.Add(frame);
                using (var jpegStream = new MemoryStream())
                {
                    encoder.Save(jpegStream);

                    if (writer.BaseStream == null || writer.BaseStream.CanWrite == false)
                        return;

                    // Header
                    writer.Write(this.OutputWidth);
                    writer.Write(this.OutputHeight);
                    writer.Write((int)jpegStream.Length);

                    // Data
                    jpegStream.Position = 0;
                    jpegStream.CopyTo(writer.BaseStream);
                }
            });
        }
Example #15
0
        public void DrawImage(Image image, float x, float y, float width, float height)
        {
            var src = image.ToWpf((int)Math.Max(width, height));

            if ((imageInterpolation == Eto.Drawing.ImageInterpolation.High || imageInterpolation == Eto.Drawing.ImageInterpolation.Default) &&
                (width != src.Width || height != src.Height))
            {
                // better image quality by using transformed bitmap, plus it is actually faster
                src = new swmi.TransformedBitmap(
                    src,
                    new swm.ScaleTransform(width / src.Width * 96 / src.DpiX, height / src.Height * 96 / src.DpiY, 0, 0)
                    );
            }
            Control.DrawImage(src, new sw.Rect(x + inverseoffset, y + inverseoffset, width, height));
        }
Example #16
0
		public async void Initialize()
		{
			_tempBitmapFile = await _page.GenerateThumbnail();

			Uri uri = new Uri(_tempBitmapFile.FileName, UriKind.Absolute);
			var image = new BitmapImage();
			image.BeginInit();
			image.CacheOption = BitmapCacheOption.OnLoad;
			image.UriSource = uri;
			image.EndInit();

			TransformedBitmap transformed = new TransformedBitmap(image, new RotateTransform(0));
			Image.Value = transformed;
			IsGeneratingImage.Value = false;
		}
        private static BitmapFrame GetBitmapFrame(MemoryStream original, int width, int height, BitmapScalingMode mode)
        {
            BitmapDecoder photoDecoder = BitmapDecoder.Create(original, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
            BitmapFrame photo = photoDecoder.Frames[0];

            TransformedBitmap target = new TransformedBitmap(
                photo,
                new ScaleTransform(
                    width / photo.Width * 96 / photo.DpiX,
                    height / photo.Height * 96 / photo.DpiY,
                    0, 0));
            BitmapFrame thumbnail = BitmapFrame.Create(target);
            BitmapFrame newPhoto = Resize(thumbnail, width, height, mode);

            return newPhoto;
        }
Example #18
0
        public void DrawImage(Image image, float x, float y, float width, float height)
        {
            SetOffset(true);
            var src = image.ToWpf((int)Math.Max(width, height));

            if ((ImageInterpolation == ImageInterpolation.High || ImageInterpolation == ImageInterpolation.Default) &&
                (width != src.Width || height != src.Height))
            {
                // better image quality by using transformed bitmap, plus it is actually faster
                src = new swmi.TransformedBitmap(
                    src,
                    new swm.ScaleTransform(width / src.Width * 96 / src.DpiX, height / src.Height * 96 / src.DpiY, 0, 0)
                    );
            }
            Control.DrawImage(src, WpfExtensions.NormalizedRect(x, y, width, height));
        }
Example #19
0
        public ScannedImagesModel RotateImage( int rotate )
        {
            var bitmap = GetBitmapImage();

            var rotated = new TransformedBitmap();
            rotated.BeginInit();
            rotated.Source = bitmap;
            var transform = new RotateTransform( rotate );
            rotated.Transform = transform;
            rotated.EndInit();

            // get temporary file
            var filename = PathUtility.GetTempFileName();
            var landscape = ( rotate == 90 || rotate == 270 ) ? !Landscape : Landscape;

            SaveImage( rotated, filename );

            return new ScannedImagesModel( filename, landscape );
        }
Example #20
0
        internal static void GenerateThumbnail(Stream image, string path)
        {
            BitmapFrame img = BitmapFrame.Create(image);
            double scale = 300.0 / Math.Min(img.PixelHeight, img.PixelWidth);

            TransformedBitmap scaled = new TransformedBitmap(img, new ScaleTransform(scale, scale));

            int startX = (scaled.PixelWidth - 300) / 2;
            int startY = (scaled.PixelHeight - 300) / 2;
            CroppedBitmap cropped = new CroppedBitmap(scaled, new Int32Rect(startX, startY, 300, 300));

            BitmapSource rotated = ApplyOrientation(cropped, img.Metadata as BitmapMetadata);
            using (Stream t = File.Create(path))
            {
                JpegBitmapEncoder jpg = new JpegBitmapEncoder();
                jpg.Frames.Add(BitmapFrame.Create(rotated));
                jpg.Save(t);
            }
        }
        public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream, string> pictureAvailable, Action assumeCancelled)
        {
            var filePicker = new OpenFileDialog();
            filePicker.Filter = "Image Files (*.jpg, *.jpeg)|*.jpg;*.jpeg";
            filePicker.Multiselect = false;

            if (filePicker.ShowDialog() == true)
            {
                try
                {
                    var bm = new Bitmap(filePicker.FileName);
                    if (bm != null)
                    {
                        int targetWidth;
                        int targetHeight;

                        MvxPictureDimensionHelper.TargetWidthAndHeight(maxPixelDimension, bm.Width, bm.Height, out targetWidth, out targetHeight);
                        var transformBM = new TransformedBitmap(ConvertBitmapInBitmapSource(bm), new ScaleTransform(targetWidth / (double)bm.Width, targetHeight / (double)bm.Height));

                        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                        encoder.QualityLevel = percentQuality;

                        MemoryStream stream = new MemoryStream();
                        encoder.Frames.Add(BitmapFrame.Create(transformBM));
                        encoder.Save(stream);

                        stream.Position = 0;

                        pictureAvailable(stream, filePicker.FileName);
                    }
                }
                catch (ArgumentException)
                {
                    assumeCancelled();
                }
            }
            else
            {
                assumeCancelled();
            }
        }
Example #22
0
        private static async Task<ImageAndSource> DecreaseImage(string inputFile)
        {
            var newLenght = maxFileLenght * 3;

            var initialLength = new FileInfo(inputFile).Length;

            var initialImage = await FileToImage(inputFile).ConfigureAwait(false);
            
            while (true)
            {
                using (var scaledImage = new MemoryStream())
                {
                    var scale = Math.Sqrt((((double)newLenght) / initialLength));

                    var transformed = new TransformedBitmap(initialImage, new ScaleTransform(scale, scale));

                    transformed.Freeze();

                    var saver = new JpegBitmapEncoder();

                    saver.Frames.Add(BitmapFrame.Create(transformed));

                    saver.Save(scaledImage);

                    scaledImage.Seek(0, SeekOrigin.Begin);

                    newLenght = newLenght * 4 / 5;

                    if (scaledImage.Length < maxFileLenght)
                    {
                        return new ImageAndSource
                        {
                            image = transformed,
                            source = scaledImage.ToArray()
                        };
                    }
                }
            }
        }
Example #23
0
        /// <summary>
        /// i dont know why i had to do all this bs, and for some reason i can't use it without screwing everything up...
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static Bitmap GetThumbnail(string filePath)
        {
            ShellFile    shellFile    = ShellFile.FromFilePath(filePath);
            BitmapSource bitmapSource = shellFile.Thumbnail.ExtraLargeBitmapSource;

            double newWidthRatio  = 64 / (double)bitmapSource.PixelWidth;
            double newHeightRatio = ((64 * bitmapSource.PixelHeight) / (double)bitmapSource.PixelWidth) / (double)bitmapSource.PixelHeight;

            System.Windows.Media.Imaging.BitmapSource transformedBitmapSource = new System.Windows.Media.Imaging.TransformedBitmap(
                bitmapSource,
                new System.Windows.Media.ScaleTransform(newWidthRatio, newHeightRatio));

            int width  = transformedBitmapSource.PixelWidth;
            int height = transformedBitmapSource.PixelHeight;
            int stride = width * ((transformedBitmapSource.Format.BitsPerPixel + 7) / 8);

            byte[] bits = new byte[height * stride];

            transformedBitmapSource.CopyPixels(bits, stride, 0);

            unsafe
            {
                fixed(byte *pBits = bits)
                {
                    IntPtr ptr = new IntPtr(pBits);

                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(
                        width,
                        height,
                        stride,
                        System.Drawing.Imaging.PixelFormat.Format32bppArgb,
                        ptr);

                    bitmap = new Bitmap(filePath);
                    return(bitmap);
                }
            }
        }
Example #24
0
		public static Stream ResizeImage(byte[] image, int size)
		{
			using (var imageStream = new MemoryStream(image))
			{
				var bitmap = BitmapDecoder.Create(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None).Frames[0];
				int width = bitmap.Width > bitmap.Height ? size : (int)(bitmap.Width * size / bitmap.Height);
				int height = bitmap.Width > bitmap.Height ? (int)(bitmap.Height * size / bitmap.Width) : size;
				var transformedBitmap = new TransformedBitmap(bitmap, new ScaleTransform(width / bitmap.Width, height / bitmap.Height, 0, 0));
				var resizedBitmap = BitmapFrame.Create(transformedBitmap);
				var convertedBitmap = new FormatConvertedBitmap(resizedBitmap, PixelFormats.Bgra32, null, 0);
				int stride = convertedBitmap.PixelWidth * (convertedBitmap.Format.BitsPerPixel / 8);
				byte[] data = new byte[stride * convertedBitmap.PixelHeight];
				convertedBitmap.CopyPixels(data, stride, 0);
				var writeBitmap = new WriteableBitmap(size, size, convertedBitmap.DpiX, convertedBitmap.DpiY, PixelFormats.Bgra32, null);
				writeBitmap.WritePixels(new Int32Rect(0, 0, convertedBitmap.PixelWidth, convertedBitmap.PixelHeight), data, stride, 0);
				MemoryStream resizeStream = new MemoryStream();
				PngBitmapEncoder decoder = new PngBitmapEncoder();
				decoder.Frames.Add(BitmapFrame.Create(writeBitmap));
				decoder.Save(resizeStream);
				resizeStream.Position = 0;
				return resizeStream;
			}
		}
        private void handleFrameFn(object sender, FrameReadyEventArgs e)
        {
            //    Int32Rect cropRect = new Int32Rect(400, 380, 300, 200);
            //    BitmapSource croppedImage = new CroppedBitmap(e.BitmapImage, cropRect);
            //    image4.Source = croppedImage;

            if (_rotationAngle != 0)
            {
                TransformedBitmap tmpImage = new TransformedBitmap();

                tmpImage.BeginInit();
                tmpImage.Source = e.BitmapImage; // of type BitmapImage

                RotateTransform transform = new RotateTransform(_rotationAngle);
                tmpImage.Transform = transform;
                tmpImage.EndInit();

                _dispImage.Source = tmpImage;
            }
            else
            {
                _dispImage.Source = e.BitmapImage;
            }
        }
Example #26
0
        public static void writeImage(String outputPath, BitmapSource image, Dictionary<String, Object> options = null, ImageMetadata metaData = null, CancellableOperationProgressBase progress = null)
        {            
            int width = image.PixelWidth;
            int height = image.PixelHeight;

            float scale = ImageUtils.resizeRectangle(width, height, Constants.MAX_THUMBNAIL_WIDTH, Constants.MAX_THUMBNAIL_HEIGHT);

            TransformedBitmap thumbnail = new TransformedBitmap(image, new System.Windows.Media.ScaleTransform(scale, scale));
          
            if (options != null)
            {                
                if (options.ContainsKey("Width"))
                {
                    width = (int)options["Width"];

                    if (!options.ContainsKey("Height"))
                    {
                        height = (int)(((float)width / image.PixelWidth) * image.PixelHeight);
                    }

                } 
                
                if (options.ContainsKey("Height")) {

                    height = (int)options["Height"];

                    if (!options.ContainsKey("Width"))
                    {
                        width = (int)(((float)height / image.PixelHeight) * image.PixelWidth);
                    }
                }
            }

            BitmapSource outImage = image;

            if (width != image.PixelWidth || height != image.PixelHeight)
            {      
                outImage = new TransformedBitmap(image, new System.Windows.Media.ScaleTransform((double)width / image.PixelWidth, (double)height / image.PixelHeight));
            }
          
            ImageFormat format = MediaFormatConvert.fileNameToImageFormat(outputPath);

            BitmapEncoder encoder = null;

            if (format == ImageFormat.Jpeg)
            {
                encoder = configureJpeg(options, ref thumbnail);
            }
            else if (format == ImageFormat.Png)
            {
                encoder = configurePng(options);                
            }
            else if (format == ImageFormat.Gif)
            {
                encoder = new GifBitmapEncoder();               
            }
            else if (format == ImageFormat.Bmp)
            {
                encoder = new BmpBitmapEncoder();
            }
            else if (format == ImageFormat.Tiff)
            {
                encoder = configureTiff(options);                
            }

            encoder.Frames.Add(BitmapFrame.Create(outImage, thumbnail, null, null));

            FileStream outputFile = new FileStream(outputPath, FileMode.Create);

            encoder.Save(outputFile);

            outputFile.Close();

            if (metaData != null)
            {
                metaData.Location = outputPath;
                ImageFileMetadataWriter metadataWriter = new ImageFileMetadataWriter();
                metadataWriter.writeMetadata(metaData, progress);
            }
        }
Example #27
0
        static BitmapEncoder configureJpeg(Dictionary<String, Object> options, ref TransformedBitmap thumbnail)
        {
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();

            if (options != null)
            {
                if (options.ContainsKey("QualityLevel"))
                {
                    encoder.QualityLevel = (int)options["QualityLevel"];
                }

                if (options.ContainsKey("Rotation"))
                {
                    encoder.Rotation = (Rotation)options["Rotation"];

                    if (encoder.Rotation != Rotation.Rotate0)
                    {
                        thumbnail = new TransformedBitmap(thumbnail, new System.Windows.Media.RotateTransform((int)encoder.Rotation * 90));
                    }
                }

                if (options.ContainsKey("FlipHorizontal"))
                {
                    encoder.FlipHorizontal = (bool)options["FlipHorizontal"];

                    if (encoder.FlipHorizontal)
                    {
                        System.Windows.Media.Matrix transform = System.Windows.Media.Matrix.Identity;

                        transform.M11 *= -1;
                                   
                        thumbnail = new TransformedBitmap(thumbnail, new System.Windows.Media.MatrixTransform(transform));
                    }
                }

                if (options.ContainsKey("FlipVertical"))
                {
                    encoder.FlipVertical = (bool)options["FlipVertical"];

                    if (encoder.FlipVertical)
                    {
                        System.Windows.Media.Matrix transform = System.Windows.Media.Matrix.Identity;

                        transform.M22 *= -1;

                        thumbnail = new TransformedBitmap(thumbnail, new System.Windows.Media.MatrixTransform(transform));
                    }
                }
            }

            return (encoder);
        }
        /// <summary>
        /// Scales the image to the specified size in either width or height, depending on which is closer.
        /// </summary>
        /// <param name="size">The size to scale towards</param>
        /// <returns></returns>
        public Stream ScaleImage(int size)
        {
            var rawStream = FileStream;
            using (rawStream)
            {
                rawStream.Position = 0;

                // Create bitmap decoder
                var decoder = BitmapDecoder.Create(
                rawStream,
                BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.None);

                // Decode single bitmap frame
                var frame = decoder.Frames[0];
                
                Double xRatio = frame.Width / size;
                Double yRatio = frame.Height / size;
                Double ratio = Math.Max(xRatio, yRatio);
                int nnx = (int)Math.Floor(frame.Width / ratio);
                int nny = (int)Math.Floor(frame.Height / ratio);

                // Resize the bitmap frame
                var resizedFrame = new TransformedBitmap(
                    frame,
                    new ScaleTransform(
                        nnx / frame.Width * 96 / frame.DpiX,
                        nny / frame.Height * 96 / frame.DpiY,
                        0, 0));

                // Re-encode the bitmap to stream
                var stream = new MemoryStream();
                var encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(resizedFrame));
                encoder.Save(stream);

                stream.Position = 0;
                rawStream.Dispose();
                return stream;
            }
        }
Example #29
0
        public void Draw(ApplicationContext actx, SWM.DrawingContext dc, double scaleFactor, double x, double y, ImageDescription idesc)
        {
            if (drawCallback != null) {
                DrawingContext c = new DrawingContext (dc, scaleFactor);
                actx.InvokeUserCode (delegate {
                    drawCallback (c, new Rectangle (x, y, idesc.Size.Width, idesc.Size.Height), idesc, actx.Toolkit);
                });
            }
            else {
                if (idesc.Alpha < 1)
                    dc.PushOpacity (idesc.Alpha);

                var f = GetBestFrame (actx, scaleFactor, idesc.Size.Width, idesc.Size.Height, false);
                var bmpImage = f as BitmapSource;

                // When an image is a single bitmap that doesn't have the same intrinsic size as the drawing size, dc.DrawImage makes a very poor job of down/up scaling it.
                // Thus we handle this manually by using a TransformedBitmap to handle the conversion in a better way when it's needed.

                var scaledWidth = idesc.Size.Width * scaleFactor;
                var scaledHeight = idesc.Size.Height * scaleFactor;
                if (bmpImage != null && (Math.Abs (bmpImage.PixelHeight - scaledHeight) > 0.001 || Math.Abs (bmpImage.PixelWidth - scaledWidth) > 0.001))
                    f = new TransformedBitmap (bmpImage, new ScaleTransform (scaledWidth / bmpImage.PixelWidth, scaledHeight / bmpImage.PixelHeight));

                dc.DrawImage (f, new Rect (x, y, idesc.Size.Width, idesc.Size.Height));

                if (idesc.Alpha < 1)
                    dc.Pop ();
            }
        }
Example #30
0
 private void ClonePostscript(TransformedBitmap otherTransformedBitmap)
 {
     EndInit();
 }
Example #31
0
 private static BitmapFrame Rotate(BitmapFrame photo, double angle, BitmapScalingMode mode)
 {
     TransformedBitmap target = new TransformedBitmap(
         photo,
         new RotateTransform(angle, photo.PixelWidth / 2, photo.PixelHeight / 2));
     BitmapFrame thumbnail = BitmapFrame.Create(target);
     BitmapFrame newPhoto = Resize(thumbnail, photo.PixelWidth, photo.PixelHeight, mode);
     return newPhoto;
 }
Example #32
0
        public static BitmapFrame GetBitmapFrame(BitmapFrame photo, int width, int height, BitmapScalingMode mode)
        {
            TransformedBitmap target = new TransformedBitmap(
                photo,
                new ScaleTransform(
                    width / photo.Width * 96 / photo.DpiX,
                    height / photo.Height * 96 / photo.DpiY,
                    0, 0));
            BitmapFrame thumbnail = BitmapFrame.Create(target);
            BitmapFrame newPhoto = Resize(thumbnail, width, height, mode);

            return newPhoto;
        }
Example #33
0
 private void ClonePrequel(TransformedBitmap otherTransformedBitmap)
 {
     BeginInit();
 }
Example #34
0
    /// <summary>
    /// Creates a thumbnail of the specified image
    /// </summary>
    /// <param name="thumbnailImageSource">The source filename to load a System.Drawing.Image from</param>
    /// <param name="thumbnailImageDest">Filename of the thumbnail to create</param>
    /// <param name="aThumbWidth">Maximum width of the thumbnail</param>
    /// <param name="aThumbHeight">Maximum height of the thumbnail</param>
    /// <param name="autocreateLargeThumbs">Auto create large thumbnail</param>
    /// <param name="iRotate">
    /// 0 = no rotate
    /// 1 = rotate 90 degrees
    /// 2 = rotate 180 degrees
    /// 3 = rotate 270 degrees
    /// <param name="fallBack">Needed if generated file need to be delete (for ex in temp folder)</param>
    /// </param>
    /// <returns>Whether the thumb has been successfully created</returns>
    public static bool CreateThumbnail(string thumbnailImageSource, string thumbnailImageDest, int aThumbWidth,
                                       int aThumbHeight, int iRotate, bool aFastMode, bool autocreateLargeThumbs, bool fallBack)
    {
      if (File.Exists(thumbnailImageDest))
      {
        return false;
      }

      if (string.IsNullOrEmpty(thumbnailImageSource) || string.IsNullOrEmpty(thumbnailImageDest) || aThumbHeight <= 0 ||
          aThumbHeight <= 0)
      {
        return false;
      }

      BitmapSource ret = null;
      BitmapMetadata meta = null;
      Bitmap shellThumb = null;
      Bitmap myTargetThumb = null;
      BitmapFrame frame = null;
      Image myImage = null;

      TransformedBitmap thumbnail = null;
      TransformGroup transformGroup = null;

      double angle = 0;

      bool result = false;
      int iQuality = (int) Thumbs.Quality;
      int decodeW = aThumbWidth;

      MediaUrl = thumbnailImageSource;

      try
      {
        if (fallBack)
        {
          frame = BitmapFrame.Create(new Uri(MediaUrl), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
        }
        else
        {
          //Try generate Bitmap frame : speedy and low memory !
          frame = BitmapFrame.Create(new Uri(MediaUrl), BitmapCreateOptions.DelayCreation,
                                     BitmapCacheOption.None);
        }

        if (frame.Thumbnail == null) //If it failed try second method (slower and use more memory)
        {
          using (ShellObject shellFile = ShellObject.FromParsingName(thumbnailImageSource))
          {
            shellFile.Thumbnail.RetrievalOption = ShellThumbnailRetrievalOption.Default;
            shellFile.Thumbnail.FormatOption = ShellThumbnailFormatOption.ThumbnailOnly;

            switch (iQuality)
            {
              case 0:
                shellThumb = shellFile.Thumbnail.MediumBitmap;
                break;
              case 1:
                shellThumb = shellFile.Thumbnail.LargeBitmap;
                break;
              case 2:
                shellThumb = shellFile.Thumbnail.LargeBitmap;
                break;
              case 3:
                shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;
                break;
              case 4:
                shellThumb = shellFile.Thumbnail.ExtraLargeBitmap;
                break;
              default:
                break;
            }

            switch (iRotate)
            {
              case 1:
                shellThumb.RotateFlip(RotateFlipType.Rotate90FlipNone);
                break;
              case 2:
                shellThumb.RotateFlip(RotateFlipType.Rotate180FlipNone);
                break;
              case 3:
                shellThumb.RotateFlip(RotateFlipType.Rotate270FlipNone);
                break;
              default:
                break;
            }

            if (shellThumb != null && !autocreateLargeThumbs)
            {
              int iWidth = aThumbWidth;
              int iHeight = aThumbHeight;
              double fAR = (shellThumb.Width)/((float) shellThumb.Height);

              if (shellThumb.Width > shellThumb.Height)
                iHeight = (int) Math.Floor((((float) iWidth)/fAR));
              else
                iWidth = (int) Math.Floor((fAR*((float) iHeight)));

              try
              {
                Util.Utils.FileDelete(thumbnailImageDest);
              }
              catch (Exception ex)
              {
                Log.Error("Picture: Error deleting old thumbnail - {0}", ex.Message);
              }

              // Write small thumbnail
              myTargetThumb = new Bitmap(shellThumb, iWidth, iHeight);
              myTargetThumb.Save(thumbnailImageDest, Thumbs.ThumbCodecInfo, Thumbs.ThumbEncoderParams);
              File.SetAttributes(thumbnailImageDest, File.GetAttributes(thumbnailImageDest) | FileAttributes.Hidden);
              result = true;
            }
            else
            {
              int iWidth = aThumbWidth;
              int iHeight = aThumbHeight;
              double fAR = (shellThumb.Width)/((float) shellThumb.Height);

              if (shellThumb.Width > shellThumb.Height)
                iHeight = (int) Math.Floor((((float) iWidth)/fAR));
              else
                iWidth = (int) Math.Floor((fAR*((float) iHeight)));

              try
              {
                Util.Utils.FileDelete(thumbnailImageDest);
              }
              catch (Exception ex)
              {
                Log.Error("Picture: Error deleting old thumbnail - {0}", ex.Message);
              }

              // Write Large thumbnail
              myTargetThumb = new Bitmap(shellThumb, iWidth, iHeight);
              myTargetThumb.Save(thumbnailImageDest, Thumbs.ThumbCodecInfo, Thumbs.ThumbEncoderParams);
              File.SetAttributes(thumbnailImageDest, File.GetAttributes(thumbnailImageDest) | FileAttributes.Hidden);
              result = true;
            }
          }
        }
        else
        {
          //Detect metas image
          meta = frame.Metadata as BitmapMetadata;
          ret = frame.Thumbnail;

          //if ((meta != null) && (ret != null)) //si on a des meta, tentative de récupération de l'orientation
          //{
          //  if (meta.GetQuery("/app1/ifd/{ushort=274}") != null)
          //  {
          //    orientation =
          //      (ExifOrientations)
          //      Enum.Parse(typeof (ExifOrientations), meta.GetQuery("/app1/ifd/{ushort=274}").ToString());
          //  }

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

          //  if (angle != 0) //on doit effectuer une rotation de l'image
          //  {
          //    ret = new TransformedBitmap(ret.Clone(), new RotateTransform(angle));
          //    ret.Freeze();
          //  }
          //}

          if (autocreateLargeThumbs)
          {
            if (ret != null)
            {
              // we'll make a thumbnail image then ... (too bad as the pre-created one is FAST!)
              thumbnail = new TransformedBitmap();
              thumbnail.BeginInit();
              thumbnail.Source = frame as BitmapSource;

              // we'll make a reasonable sized thumnbail
              int pixelH = frame.PixelHeight;
              int pixelW = frame.PixelWidth;
              int decodeH = (frame.PixelHeight*decodeW)/pixelW;
              double scaleX = decodeW/(double) pixelW;
              double scaleY = decodeH/(double) pixelH;

              transformGroup = new TransformGroup();
              transformGroup.Children.Add(new ScaleTransform(scaleX, scaleY));
              thumbnail.Transform = transformGroup;
              thumbnail.EndInit();
              ret = thumbnail;

              // Write Large thumbnail
              result = BitmapFromSource(ret, thumbnailImageDest);
            }
          }
          else
          {
            if (ret != null)
            {
              // Write small thumbnail
              result = BitmapFromSource(ret, thumbnailImageDest);
            }
          }
        }

      }
      catch (Exception ex)
      {
        try
        {
          try
          {
            myImage = ImageFast.FromFile(thumbnailImageSource);
          }
          catch (FileNotFoundException)
          {
            result = false;
          }
          result = CreateThumbnail(myImage, thumbnailImageDest, aThumbWidth, aThumbHeight, iRotate, aFastMode);
        }
        catch (Exception)
        {
          Log.Warn("Picture: Fast loading of thumbnail {0} failed - trying safe fallback now", thumbnailImageDest);

          try
          {
            try
            {
              myImage = ImageFast.FromFile(thumbnailImageDest);
              result = CreateThumbnail(myImage, thumbnailImageDest, aThumbWidth, aThumbHeight, iRotate, aFastMode);
            }
            catch (Exception)
            {
              myImage = Image.FromFile(thumbnailImageDest, true);
              result = CreateThumbnail(myImage, thumbnailImageDest, aThumbWidth, aThumbHeight, iRotate, aFastMode);
            }
          }
          catch (FileNotFoundException)
          {
            result = false;
          }
          catch (OutOfMemoryException)
          {
            Log.Warn("Picture: Creating thumbnail failed - image format is not supported of {0}", thumbnailImageSource);
            result = false;
          }
          catch (Exception)
          {
            Log.Info("Pictures: No thumbnail created for -- {0}", thumbnailImageSource);
            result = false;
          }
        }
      }
      finally
      {
        if (shellThumb != null)
          shellThumb.SafeDispose();
        if (ret != null)
          ret.SafeDispose();
        if (thumbnail != null)
          thumbnail.SafeDispose();
        if (transformGroup != null)
          transformGroup.SafeDispose();
        if (myTargetThumb != null)
          myTargetThumb.SafeDispose();
        if (MediaUrl != null)
          MediaUrl.SafeDispose();
        if (frame != null)
          frame.SafeDispose();
        if (myImage != null)
          myImage.SafeDispose();
      }

      if (result && Util.Utils.IsFileExistsCacheEnabled())
      {
        Log.Debug("CreateThumbnail : FileExistsInCache updated with new file: {0}", thumbnailImageDest);
        Util.Utils.DoInsertExistingFileIntoCache(thumbnailImageDest);
      }
      return result;
    }
Example #35
0
 public static ImageData CreateFlipped(ImageMetaData info, PixelFormat format, BitmapPalette palette,
                                 byte[] pixel_data, int stride)
 {
     var bitmap = BitmapSource.Create((int)info.Width, (int)info.Height, DefaultDpiX, DefaultDpiY,
                                       format, palette, pixel_data, stride);
     var flipped = new TransformedBitmap(bitmap, new ScaleTransform { ScaleY = -1 });
     flipped.Freeze();
     return new ImageData(flipped, info);
 }
Example #36
0
        internal override void FinalizeCreation()
        {
            _bitmapInit.EnsureInitializedComplete();
            Uri uri = UriSource;

            if (_baseUri != null)
            {
                uri = new Uri(_baseUri, UriSource);
            }

            if ((CreateOptions & BitmapCreateOptions.IgnoreImageCache) != 0)
            {
                ImagingCache.RemoveFromImageCache(uri);
            }

            BitmapImage bitmapImage = CheckCache(uri);

            if (bitmapImage != null &&
                bitmapImage.CheckAccess() &&
                bitmapImage.SourceRect.Equals(SourceRect) &&
                bitmapImage.DecodePixelWidth == DecodePixelWidth &&
                bitmapImage.DecodePixelHeight == DecodePixelHeight &&
                bitmapImage.Rotation == Rotation &&
                (bitmapImage.CreateOptions & BitmapCreateOptions.IgnoreColorProfile) ==
                (CreateOptions & BitmapCreateOptions.IgnoreColorProfile)
                )
            {
                _syncObject = bitmapImage.SyncObject;
                lock (_syncObject)
                {
                    WicSourceHandle   = bitmapImage.WicSourceHandle;
                    IsSourceCached    = bitmapImage.IsSourceCached;
                    _convertedDUCEPtr = bitmapImage._convertedDUCEPtr;

                    //
                    // We nee d to keep the strong reference to the cached image for a few reasons:
                    //
                    //    The application may release the original cached image and then keep a
                    //    reference to this image only, in which case, the cache can be collected.
                    //    This will cause a few undesirable results:
                    //    1. The application may choose to decode the same URI again in which case
                    //       we will not retrieve it from the cache even though we have a copy already
                    //       decoded.
                    //    2. The original cached image holds onto the file stream indirectly which if
                    //       collected can cause bad behavior if the entire image is not loaded into
                    //       memory.
                    //
                    _cachedBitmapImage = bitmapImage;
                }
                UpdateCachedSettings();
                return;
            }

            BitmapDecoder decoder = null;

            if (_decoder == null)
            {
                // Note: We do not want to insert in the cache if there is a chance that
                //       the decode pixel width/height may cause the decoder LOD to change
                decoder = BitmapDecoder.CreateFromUriOrStream(
                    _baseUri,
                    UriSource,
                    StreamSource,
                    CreateOptions & ~BitmapCreateOptions.DelayCreation,
                    BitmapCacheOption.None, // do not cache the frames since we will do that here
                    _uriCachePolicy,
                    false
                    );

                if (decoder.IsDownloading)
                {
                    _isDownloading             = true;
                    _decoder                   = decoder;
                    decoder.DownloadProgress  += OnDownloadProgress;
                    decoder.DownloadCompleted += OnDownloadCompleted;
                    decoder.DownloadFailed    += OnDownloadFailed;
                }
                else
                {
                    Debug.Assert(decoder.SyncObject != null);
                }
            }
            else
            {
                // We already had a decoder, meaning we were downloading
                Debug.Assert(!_decoder.IsDownloading);
                decoder  = _decoder;
                _decoder = null;
            }

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

            BitmapFrame  frame  = decoder.Frames[0];
            BitmapSource source = frame;

            Int32Rect sourceRect = SourceRect;

            if (sourceRect.X == 0 && sourceRect.Y == 0 &&
                sourceRect.Width == source.PixelWidth &&
                sourceRect.Height == source.PixelHeight)
            {
                sourceRect = Int32Rect.Empty;
            }

            if (!sourceRect.IsEmpty)
            {
                CroppedBitmap croppedSource = new CroppedBitmap();
                croppedSource.BeginInit();
                croppedSource.Source     = source;
                croppedSource.SourceRect = sourceRect;
                croppedSource.EndInit();

                source = croppedSource;
                if (_isDownloading)
                {
                    // Unregister the download events because this is a dummy image. See comment below.
                    source.UnregisterDownloadEventSource();
                }
            }

            int finalWidth  = DecodePixelWidth;
            int finalHeight = DecodePixelHeight;

            if (finalWidth == 0 && finalHeight == 0)
            {
                finalWidth  = source.PixelWidth;
                finalHeight = source.PixelHeight;
            }
            else if (finalWidth == 0)
            {
                finalWidth = (source.PixelWidth * finalHeight) / source.PixelHeight;
            }
            else if (finalHeight == 0)
            {
                finalHeight = (source.PixelHeight * finalWidth) / source.PixelWidth;
            }

            if (finalWidth != source.PixelWidth || finalHeight != source.PixelHeight ||
                Rotation != Rotation.Rotate0)
            {
                TransformedBitmap transformedSource = new TransformedBitmap();
                transformedSource.BeginInit();
                transformedSource.Source = source;

                TransformGroup transformGroup = new TransformGroup();

                if (finalWidth != source.PixelWidth || finalHeight != source.PixelHeight)
                {
                    int oldWidth  = source.PixelWidth;
                    int oldHeight = source.PixelHeight;

                    Debug.Assert(oldWidth > 0 && oldHeight > 0);

                    transformGroup.Children.Add(
                        new ScaleTransform(
                            (1.0 * finalWidth) / oldWidth,
                            (1.0 * finalHeight) / oldHeight));
                }

                if (Rotation != Rotation.Rotate0)
                {
                    double rotation = 0.0;

                    switch (Rotation)
                    {
                    case Rotation.Rotate0:
                        rotation = 0.0;
                        break;

                    case Rotation.Rotate90:
                        rotation = 90.0;
                        break;

                    case Rotation.Rotate180:
                        rotation = 180.0;
                        break;

                    case Rotation.Rotate270:
                        rotation = 270.0;
                        break;

                    default:
                        Debug.Assert(false);
                        break;
                    }

                    transformGroup.Children.Add(new RotateTransform(rotation));
                }

                transformedSource.Transform = transformGroup;

                transformedSource.EndInit();

                source = transformedSource;
                if (_isDownloading)
                {
                    //
                    // If we're currently downloading, then the BitmapFrameDecode isn't actually
                    // the image, it's just a 1x1 placeholder. The chain we're currently building
                    // will be replaced with another chain once download completes, so there's no
                    // need to have this chain handle DownloadCompleted.
                    //
                    // Having this chain handle DownloadCompleted is actually a bad thing. Because
                    // the dummy is just 1x1, the TransformedBitmap we're building here will have
                    // a large scaling factor (to scale the image from 1x1 up to whatever
                    // DecodePixelWidth/Height specifies). When the TransformedBitmap receives
                    // DownloadCompleted from the BFD, it will call into WIC to create a new
                    // bitmap scaler using the same large scaling factor, which can produce a huge
                    // bitmap (since the BFD is now no longer 1x1). This problem is made worse if
                    // this BitmapImage has BitmapCacheOption.OnLoad, since that will put a
                    // CachedBitmap after the TransformedBitmap. When DownloadCompleted propagates
                    // from the TransformedBitmap down to the CachedBitmap, the CachedBitmap will
                    // call CreateBitmapFromSource using the TransformedBitmap, which calls
                    // CopyPixels on the huge TransformedBitmap. We want to avoid chewing up the
                    // CPU and the memory, so we unregister the download event handlers here.
                    //
                    source.UnregisterDownloadEventSource();
                }
            }

            //
            // If the original image has a color profile and IgnoreColorProfile is not one of the create options,
            // apply the profile so bits are color-corrected.
            //
            if ((CreateOptions & BitmapCreateOptions.IgnoreColorProfile) == 0 &&
                frame.ColorContexts != null &&
                frame.ColorContexts[0] != null &&
                frame.ColorContexts[0].IsValid &&
                source.Format.Format != PixelFormatEnum.Extended
                )
            {
                // NOTE: Never do this for a non-MIL pixel format, because the format converter has
                // special knowledge to deal with the profile

                PixelFormat  duceFormat   = BitmapSource.GetClosestDUCEFormat(source.Format, source.Palette);
                bool         changeFormat = (source.Format != duceFormat);
                ColorContext destinationColorContext;

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

                if (destinationColorContext != null)
                {
                    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(
                            source,
                            frame.ColorContexts[0],
                            destinationColorContext,
                            duceFormat
                            );

                        source = colorConvertedBitmap;
                        if (_isDownloading)
                        {
                            // Unregister the download events because this is a dummy image. See comment above.
                            source.UnregisterDownloadEventSource();
                        }
                        conversionSuccess = true;
                    }
                    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 && !badColorContext && changeFormat)
                    {   // If the conversion failed, we first use
                        // a FormatConvertedBitmap, and then Color Convert that one...
                        FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(source, duceFormat, source.Palette, 0.0);

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

                        source = colorConvertedBitmap;
                        if (_isDownloading)
                        {
                            // Unregister the download events because this is a dummy image. See comment above.
                            source.UnregisterDownloadEventSource();
                        }
                    }
                }
            }

            if (CacheOption != BitmapCacheOption.None)
            {
                try
                {
                    // The bitmaps bits could be corrupt, and this will cause an exception if the CachedBitmap forces a decode.
                    CachedBitmap cachedSource = new CachedBitmap(source, CreateOptions & ~BitmapCreateOptions.DelayCreation, CacheOption);
                    source = cachedSource;
                    if (_isDownloading)
                    {
                        // Unregister the download events because this is a dummy image. See comment above.
                        source.UnregisterDownloadEventSource();
                    }
                }
                catch (Exception e)
                {
                    RecoverFromDecodeFailure(e);
                    CreationCompleted = true; // we're bailing out because the decode failed
                    return;
                }
            }

            // If CacheOption == OnLoad, no need to keep the stream around
            if (decoder != null && CacheOption == BitmapCacheOption.OnLoad)
            {
                decoder.CloseStream();
            }
            else if (CacheOption != BitmapCacheOption.OnLoad)
            {
                //ensure that we don't GC the source
                _finalSource = source;
            }

            WicSourceHandle = source.WicSourceHandle;
            IsSourceCached  = source.IsSourceCached;

            CreationCompleted = true;
            UpdateCachedSettings();

            // Only insert in the imaging cache if download is complete
            if (!IsDownloading)
            {
                InsertInCache(uri);
            }
        }