private void Image_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { var AssociatedObject = this; // Retrieve the coordinate of the mouse position in relation to the supplied image. Point point = e.GetPosition(AssociatedObject); // Use RenderTargetBitmap to get the visual, in case the image has been transformed. var renderTargetBitmap = new RenderTargetBitmap((int) AssociatedObject.ActualWidth, (int) AssociatedObject.ActualHeight, 96, 96, PixelFormats.Default); renderTargetBitmap.Render(AssociatedObject); // Make sure that the point is within the dimensions of the image. if ((point.X <= renderTargetBitmap.PixelWidth) && (point.Y <= renderTargetBitmap.PixelHeight)) { // Create a cropped image at the supplied point coordinates. var croppedBitmap = new CroppedBitmap(renderTargetBitmap, new Int32Rect((int) point.X, (int) point.Y, 1, 1)); // Copy the sampled pixel to a byte array. var pixels = new byte[4]; croppedBitmap.CopyPixels(pixels, 4, 0); // Assign the sampled color to a SolidColorBrush and return as conversion. var SelectedColor = Color.FromArgb(255, pixels[2], pixels[1], pixels[0]); TextBox.Text = "#" + SelectedColor.ToString().Substring(3); Label.Background = new SolidColorBrush(SelectedColor); } }
public void PageLoaded(object sender, RoutedEventArgs args) { // Create an Image element. Image croppedImage = new Image(); croppedImage.Width = 200; croppedImage.Margin = new Thickness(5); // Create a CroppedBitmap based off of a xaml defined resource. CroppedBitmap cb = new CroppedBitmap( (BitmapSource)this.Resources["masterImage"], new Int32Rect(30, 20, 105, 50)); //select region rect croppedImage.Source = cb; //set image source to cropped // Add Image to the UI Grid.SetColumn(croppedImage, 1); Grid.SetRow(croppedImage, 1); croppedGrid.Children.Add(croppedImage); // Create an Image element. Image chainImage = new Image(); chainImage.Width = 200; chainImage.Margin = new Thickness(5); // Create the cropped image based on previous CroppedBitmap. CroppedBitmap chained = new CroppedBitmap(cb, new Int32Rect(30, 0, (int)cb.Width-30, (int)cb.Height)); // Set the image's source. chainImage.Source = chained; // Add Image to the UI. Grid.SetColumn(chainImage, 1); Grid.SetRow(chainImage, 3); croppedGrid.Children.Add(chainImage); }
private void Image_MouseDown(object sender, MouseButtonEventArgs e) { try { var cb = new CroppedBitmap((BitmapSource) (((Image) e.Source).Source), new Int32Rect((int) Mouse.GetPosition(e.Source as Image).X, (int) Mouse.GetPosition(e.Source as Image).Y, 1, 1)); _pixels = new byte[4]; try { cb.CopyPixels(_pixels, 4, 0); SetColor(Color.FromRgb(_pixels[2], _pixels[1], _pixels[0])); UpdateMarkerPosition(); if (OnColorSelected != null) OnColorSelected(SelectedColor); } catch { // not logged } UpdateSlider(); } catch (Exception) { // not logged } }
/// <summary>Creates the screenshot of entire plotter element</summary> /// <returns></returns> internal static BitmapSource CreateScreenshot(UIElement uiElement, Int32Rect screenshotSource) { Window window = Window.GetWindow(uiElement); if (window == null) { return CreateElementScreenshot(uiElement); } Size size = window.RenderSize; //double dpiCoeff = 32 / SystemParameters.CursorWidth; //int dpi = (int)(dpiCoeff * 96); double dpiCoeff = 1; int dpi = 96; RenderTargetBitmap bmp = new RenderTargetBitmap( (int)(size.Width * dpiCoeff), (int)(size.Height * dpiCoeff), dpi, dpi, PixelFormats.Default); // white background Rectangle whiteRect = new Rectangle { Width = size.Width, Height = size.Height, Fill = Brushes.White }; whiteRect.Measure(size); whiteRect.Arrange(new Rect(size)); bmp.Render(whiteRect); // the very element bmp.Render(uiElement); CroppedBitmap croppedBmp = new CroppedBitmap(bmp, screenshotSource); return croppedBmp; }
//------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void SourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CroppedBitmap target = ((CroppedBitmap)d); target.SourcePropertyChangedHook(e); // The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children) // will promote the property value from a default value to a local value. This is technically a sub-property // change because the collection was changed and not a new collection set (GeometryGroup.Children. // Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled // the default value to the compositor. If the property changes from a default value, the new local value // needs to be marshalled to the compositor. We detect this scenario with the second condition // e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be // Default and the NewValueSource will be Local. if (e.IsASubPropertyChange && (e.OldValueSource == e.NewValueSource)) { return; } target.PropertyChanged(SourceProperty); }
public void DrawImage(BasicRectangle rectangleDestination, BasicRectangle rectangleSource, IDisposable image) { // Make sure the source rectangle width isn't out of bounds var disposableImage = (DisposableBitmap)image; var croppedBitmap = new CroppedBitmap(disposableImage.Bitmap, GenericControlHelper.ToInt32Rect(rectangleSource)); _context.DrawImage(croppedBitmap, GenericControlHelper.ToRect(rectangleDestination)); }
private Color GetColorFromImage(Point p) { try { var bounds = VisualTreeHelper.GetDescendantBounds(this); var rtb = new RenderTargetBitmap((int) bounds.Width, (int) bounds.Height, 96, 96, PixelFormats.Default); rtb.Render(this); byte[] arr; var png = new PngBitmapEncoder(); png.Frames.Add(BitmapFrame.Create(rtb)); using (var stream = new MemoryStream()) { png.Save(stream); arr = stream.ToArray(); } BitmapSource bitmap = BitmapFrame.Create(new MemoryStream(arr)); var pixels = new byte[4]; var cb = new CroppedBitmap(bitmap, new Int32Rect((int) p.X, (int) p.Y, 1, 1)); cb.CopyPixels(pixels, 4, 0); return Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]); } catch (Exception) { return ColorBox.Color; } }
private Color GetColorFromImage() { var color = Colors.Transparent; try { BitmapSource bitmapSource = ImageColors.Source as BitmapSource; if (bitmapSource != null) { double x = Mouse.GetPosition(ImageColors).X; x *= bitmapSource.PixelWidth / ImageColors.ActualWidth; if ((int)x > bitmapSource.PixelWidth - 1) x = bitmapSource.PixelWidth - 1; else if (x < 0) x = 0; double y = Mouse.GetPosition(ImageColors).Y; y *= bitmapSource.PixelHeight / ImageColors.ActualHeight; if ((int)y > bitmapSource.PixelHeight - 1) y = bitmapSource.PixelHeight - 1; else if (y < 0) y = 0; CroppedBitmap cb = new CroppedBitmap(bitmapSource, new Int32Rect((int)x, (int)y, 1, 1)); byte[] pixels = new byte[4]; cb.CopyPixels(pixels, 4, 0); if (pixels[3] == byte.MaxValue) { color = Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]); } } } catch (Exception ex) { Log.Add(ex); } return color; }
/// <summary> /// Generates an image of each page in the year book /// and saves it to the src folder /// </summary> /// <param name="bv"></param> /// <param name="folderloc"></param> private static void RenderPages(BookViewer bv, string folderloc) { int currentpage = bv.ViewIndex; //loops though each page foreach (Page p in bv.CurrentBook.Pages) { bv.ViewIndex = p.PageNumber; //forces the canvas to re-render BookViewer.DesignerCanvas.UpdateLayout(); //takes a picture of the canvas RenderTargetBitmap rtb = new RenderTargetBitmap(PaperSize.Pixel.PaperWidth, PaperSize.Pixel.PaperHeight, 96, 96, PixelFormats.Default); rtb.Render(BookViewer.DesignerCanvas); //getting the bleed margin Int32Rect bleedmargin = new Int32Rect((PaperSize.Pixel.PaperWidth - PaperSize.Pixel.BleedWidth) / 2, (PaperSize.Pixel.PaperHeight - PaperSize.Pixel.BleedHeight) / 2, PaperSize.Pixel.BleedWidth, PaperSize.Pixel.BleedHeight); //cropping the image CroppedBitmap cb = new CroppedBitmap(rtb, bleedmargin); //encodes the image in png format PngBitmapEncoder pbe = new PngBitmapEncoder(); pbe.Frames.Add(BitmapFrame.Create(cb)); //saves the resulting image FileStream fs = File.Open(folderloc + "\\src\\" + (p.PageNumber+1) + ".png", FileMode.Create); pbe.Save(fs); fs.Flush(); fs.Close(); } bv.ViewIndex = currentpage; }
public CardPack() { _pack = new List<Card>(); Uri uri = new Uri("./Images/cards.png", UriKind.Relative); source = new BitmapImage(uri); _cardFronts = new List<CroppedBitmap>(); CardBack = new Image(); int w = source.PixelWidth / 13; int h = source.PixelHeight/5; for (int s = 0; s < 4; s++) { for (int v = 0; v < 13; v++) { int imageIndex = (s*13) + v; int fx = imageIndex % 13; int fy = imageIndex / 13; Int32Rect sourceRect = new Int32Rect(fx * w, fy * h, w, h); CroppedBitmap front = new CroppedBitmap(source, sourceRect); sourceRect = new Int32Rect(2 * w, 4 * h, w, h); CroppedBitmap back = new CroppedBitmap(source, sourceRect); Image frontImage = new Image {Source = front}; Image backImage = new Image { Source = back }; Card card = new Card((CardSuit)s, (CardValue)v, frontImage, backImage); _pack.Add(card); } } }
public Pieza(int valor, int fila, int columna, CroppedBitmap imagen) { Valor = valor; Fila = fila; Columna = columna; Imagen = imagen; }
private static ImageSource GetImageSource() { BitmapSource source = ImageHelper.BitmapSourceFromBitmap(new Bitmap(Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("Paket.VisualStudio.Resources.NuGet.ico")))); Int32Rect sourceRect = new Int32Rect(0, 0, 16, 16); ImageSource imageSource = new CroppedBitmap(source, sourceRect); imageSource.Freeze(); return imageSource; }
private static void SourceRectPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { CroppedBitmap target = ((CroppedBitmap)d); target.SourceRectPropertyChangedHook(e); target.PropertyChanged(SourceRectProperty); }
public Image MakeImage() { CroppedBitmap subImg = new CroppedBitmap(RootImage, Region); Image res = new Image(); res.Source = subImg; return res; }
public Task<BitmapSource> TakePartialScreenshot(Int32Rect rpRect) { return TakeScreenshot(r => { var rResult = new CroppedBitmap(r, rpRect); rResult.Freeze(); return rResult; }); }
public CroppedBitmap GetBitMap(int id) { var p = GetPosition(id); var bitmap = new CroppedBitmap(); bitmap.BeginInit(); bitmap.Source = _imageSource; bitmap.SourceRect = new Int32Rect(p.X * _cropSize, p.Y * _cropSize, _cropSize, _cropSize); bitmap.EndInit(); return bitmap; }
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; }
public void upload(CroppedBitmap image) { PngBitmapEncoder pngEncoder = new PngBitmapEncoder(); pngEncoder.Frames.Add(BitmapFrame.Create(image)); String uniqid = Guid.NewGuid().ToString(); FileStream stream = new FileStream(uniqid, FileMode.Create); pngEncoder.Save(stream); stream.Close(); String response = PostToImageShack(uniqid); parseResponse(response); }
/// <summary> /// Coerce SourceRect /// </summary> private static object CoerceSourceRect(DependencyObject d, object value) { CroppedBitmap bitmap = (CroppedBitmap)d; if (!bitmap._bitmapInit.IsInInit) { return(bitmap._sourceRect); } else { return(value); } }
public static System.Windows.Controls.Image Crop(Panel displayer, double x, double y, double Width, double Height) { if (displayer == null) return null; Rect rect = new Rect(displayer.RenderSize); RenderTargetBitmap rtb = new RenderTargetBitmap((int)rect.Right, (int)rect.Bottom, 96d, 96d, System.Windows.Media.PixelFormats.Default); rtb.Render(displayer); var crop = new CroppedBitmap(rtb, new Int32Rect((int)x, (int)y, (int)Width, (int)Height)); return new System.Windows.Controls.Image() { Source = BitmapFrame.Create(crop) }; }
/// <summary> /// Implementation of Freezable.GetCurrentValueAsFrozenCore() /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { CroppedBitmap sourceCroppedBitmap = (CroppedBitmap)source; // Set any state required before actual clone happens ClonePrequel(sourceCroppedBitmap); base.GetCurrentValueAsFrozenCore(source); // Set state once clone has finished ClonePostscript(sourceCroppedBitmap); }
void Calc() { var xsize = Parent.ImageSource.PixelWidth / Parent.MaxColumns; var ysize = Parent.ImageSource.PixelHeight / Parent.MaxColumns; var col = Index % Parent.MaxColumns; var row = Index / Parent.MaxColumns; var x = xsize * col; var y = ysize * row; var rect = new Int32Rect(x, y, xsize, ysize); ImageSource = new CroppedBitmap(Parent.ImageSource, rect); }
protected BitmapSource CropImage(BitmapSource image, Rectangle ClippingRectangle) { // Create a CroppedBitmap based off of a xaml defined resource. CroppedBitmap cb = new CroppedBitmap( image, //select region rect new Int32Rect( (int)Canvas.GetLeft(ClippingRectangle), (int)Canvas.GetTop(ClippingRectangle), (int)ClippingRectangle.Width, (int)ClippingRectangle.Height)); return cb; }
public AnimationFrameViewModel(SubTexture subTexture, BitmapImage image) { this.Name = subTexture.Name; this.X = subTexture.X; this.Y = subTexture.Y; this.Width = subTexture.Width; this.Height = subTexture.Height; Int32 frameIndex = -1; //There should be 4 padding zeros Int32.TryParse(Name.Substring(Name.Length - 4, 4), out frameIndex); this.Index = frameIndex; this.frameImage = new CroppedBitmap(image, new System.Windows.Int32Rect(x, y, width, height)); }
public MainViewModel(IEventAggregator eventAggregator) { this.eventAggregator = eventAggregator; //eventAggregator.Subscribe(this); animationTimer.AutoReset = true; animationTimer.Elapsed += animationTimer_Elapsed; try { defaultImage = new BitmapImage(new Uri(@"pack://application:,,,/Content/default.png")); defaultCroppedImage = new CroppedBitmap(defaultImage, new System.Windows.Int32Rect(10, 10, 280, 280)); } catch (Exception ex) { String debugMe = ex.Message; } }
private void BtnClip_Click(object sender, RoutedEventArgs e) { BitmapImage myBitmapImage = new BitmapImage(); // BitmapSource objects like BitmapImage can only have their properties// changed within a BeginInit/EndInit block. myBitmapImage.BeginInit(); myBitmapImage.UriSource = new Uri("pack://application:,,,/Images/xiaoxiong.jpg"); //myBitmapImage.DecodePixelWidth = 200; myBitmapImage.EndInit(); // Create a CroppedBitmap based off of a xaml defined resource. CroppedBitmap cb = new CroppedBitmap( (BitmapSource)myBitmapImage, new Int32Rect(10, 20, 15, 25)); //select region rect img3.Source = cb; }
public ICollection<ImageSource> getImageSources() { int row = (int)(img.PixelHeight-2*margin)/tileHeight; int col = (int)(img.PixelWidth - 2 * margin) / tileWidth; int size = row * col; ImageSource[] retVal = new ImageSource[size]; int count = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { retVal[count++] = new CroppedBitmap(img, new Int32Rect(margin + j * tileWidth, margin + i * tileHeight, tileWidth, tileHeight)); } } return retVal; }
public SparkleSpinner (int size) : base () { if (DesignerProperties.GetIsInDesignMode(this)) { return; } Width = size; Height = size; int current_frame = 0; BitmapSource spinner_gallery = SparkleUIHelpers.GetImageSource ("process-working-22"); int frames_in_width = spinner_gallery.PixelWidth / size; int frames_in_height = spinner_gallery.PixelHeight / size; int frame_count = (frames_in_width * frames_in_height) - 1; Image [] frames = new Image [frame_count]; int i = 0; for (int y = 0; y < frames_in_height; y++) { for (int x = 0; x < frames_in_width; x++) { if (!(y == 0 && x == 0)) { CroppedBitmap crop = new CroppedBitmap (spinner_gallery, new Int32Rect (size * x, size * y, size, size)); frames [i] = new Image (); frames [i].Source = crop; i++; } } } this.timer = new Timer () { Interval = 400 / frame_count }; this.timer.Elapsed += delegate { Dispatcher.BeginInvoke ((Action) delegate { if (current_frame < frame_count - 1) current_frame++; else current_frame = 0; Source = frames [current_frame].Source; }); }; }
public SparkleSpinner(int size) : base() { Width = size; Height = size; BitmapSource spinner_gallery = SparkleUIHelpers.GetImageSource ("process-working-22"); int frames_in_width = spinner_gallery.PixelWidth / size; int frames_in_height = spinner_gallery.PixelHeight / size; this.num_steps = (frames_in_width * frames_in_height) - 1; this.images = new Image [this.num_steps]; int i = 0; for (int y = 0; y < frames_in_height; y++) { for (int x = 0; x < frames_in_width; x++) { if (!(y == 0 && x == 0)) { CroppedBitmap crop = new CroppedBitmap ( spinner_gallery, new Int32Rect (size * x, size * y, size, size) ); this.images [i] = new Image (); this.images [i].Source = crop; i++; } } } this.timer = new Timer () { Interval = 400 / this.num_steps }; this.timer.Elapsed += delegate { Dispatcher.Invoke ((Action) delegate { NextImage (); }); }; Start (); }
public static BitmapImage Crop(this BitmapImage bmp, Int32Rect rct) { CroppedBitmap croppedBmp = new CroppedBitmap(bmp, rct); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); MemoryStream memoryStream = new MemoryStream(); BitmapImage bImg = new BitmapImage(); encoder.Frames.Add(BitmapFrame.Create(croppedBmp)); encoder.Save(memoryStream); bImg.BeginInit(); bImg.CacheOption = BitmapCacheOption.OnLoad; bImg.StreamSource = new MemoryStream(memoryStream.ToArray()); bImg.EndInit(); memoryStream.Close(); return bImg; }
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); } }
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.back = ((System.Windows.Controls.Button)(target)); #line 47 "..\..\..\..\Views\GameTuChon\Game4.xaml" this.back.Click += new System.Windows.RoutedEventHandler(this.back_Click); #line default #line hidden return; case 2: this.btnLoadFromFile = ((System.Windows.Controls.Button)(target)); #line 52 "..\..\..\..\Views\GameTuChon\Game4.xaml" this.btnLoadFromFile.Click += new System.Windows.RoutedEventHandler(this.BtnLoadFromFile_Click); #line default #line hidden return; case 3: this.abc = ((System.Windows.Controls.Image)(target)); return; case 4: this.anh = ((System.Windows.Media.Imaging.CroppedBitmap)(target)); return; case 5: this.abcd = ((System.Windows.Controls.Image)(target)); return; case 6: this.anh1 = ((System.Windows.Media.Imaging.CroppedBitmap)(target)); return; } this._contentLoaded = true; }
public virtual IDisposable DrawPortion(DrawingContext drawingContext, Rect targetItemRectangle, Rect sourceRectangle, int level) { //Do not dispose the memory stream here, because System.Media.Windows uses // retained mode rendering where the commands get batched to execute later. MemoryStream imageStream = new MemoryStream(ImageData); try { BitmapSource source = BitmapFromJpeg(imageStream); Int32Rect cropRect = Int32RectFromRect(sourceRectangle); CroppedBitmap croppedImage = new CroppedBitmap(source, cropRect); drawingContext.DrawImage(croppedImage, targetItemRectangle); return imageStream; //Return our stream so it can be disposed later. } catch { if (imageStream != null) imageStream.Dispose(); throw; } }
void wheel_MouseMove(object sender, MouseEventArgs e) { try { CroppedBitmap cb = new CroppedBitmap(wheel.Source as BitmapSource, new Int32Rect((int)Mouse.GetPosition(this).X, (int)Mouse.GetPosition(this).Y, 1, 1)); pixels = new byte[4]; try { cb.CopyPixels(pixels, 4, 0); } catch (Exception ex) { MessageBox.Show(ex.Message); } Console.WriteLine(pixels[0] + ":" + pixels[1] + ":" + pixels[2] + ":" + pixels[3]); rec.Fill = new SolidColorBrush(System.Windows.Media.Color.FromRgb(pixels[2], pixels[1], pixels[0])); } catch (Exception exc) { } }
private void Image_MouseDown(object sender, MouseButtonEventArgs e) { try { var cb = new CroppedBitmap((BitmapSource)(((Image)e.Source).Source), new Int32Rect((int)Mouse.GetPosition(e.Source as Image).X, (int)Mouse.GetPosition(e.Source as Image).Y, 1, 1)); _pixels = new byte[4]; try { cb.CopyPixels(_pixels, 4, 0); UpdateCurrentColor(); UpdateMarkerPosition(); } catch { } UpdateSlider(); } catch (Exception) { } }
private void ClonePrequel(CroppedBitmap otherCroppedBitmap) { BeginInit(); }
private void ClonePostscript(CroppedBitmap otherCroppedBitmap) { EndInit(); }
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); } }