This project has moved. For the latest updates, please go here.

Handle BitmapSource as source

Jun 9, 2011 at 11:39 AM
Edited Jun 9, 2011 at 11:41 AM

Hiya

I've been using your library to grey out my images but recently I switched to using the WPF localize extension (from here: http://wpflocalizeextension.codeplex.com/) as my way of setting the source for an image. Unfortunately that tripped up GreyableImage because it thinks the source is an URI while it is actually a BitmapSource (or more specifically an InteropBitmap). In order to allow GreyableImage to read these bitmaps I made the following changes to the source:

In ImageGreyer.cs, around line 299 add the following check:

 

if (_sourceColour is BitmapSource)
{
    colourBitmap = (BitmapSource)_sourceColour;
}

 

The method should then look like:

 

private void SetSources()
{
  if (null == _image.Source)
	return;

  // in case greyscale image cannot be created set greyscale source to original Source first
  _sourceGreyscale = _sourceColour = _image.Source;

  try
  {
	BitmapSource colourBitmap;
	if (_sourceColour is BitmapSource)
	{
		colourBitmap = (BitmapSource)_sourceColour;
	}
	else
	{
		if (_sourceColour is DrawingImage)
		{
			// support for DrawingImage as a source - thanks to Morten Schou who provided this code
			colourBitmap = new RenderTargetBitmap((int)_sourceColour.Width,
							      (int)_sourceColour.Height,
							      96, 96,
							      PixelFormats.Default);
			DrawingVisual drawingVisual = new DrawingVisual();
			DrawingContext drawingDC = drawingVisual.RenderOpen();

			drawingDC.DrawImage(_sourceColour,
					    new Rect(new Size(_sourceColour.Height,
					    _sourceColour.Width)));
			drawingDC.Close();
			(colourBitmap as RenderTargetBitmap).Render(drawingVisual);
		}
		else
		{
			// get the string Uri for the original image source first
			String stringUri = TypeDescriptor.GetConverter(_sourceColour).ConvertTo(_sourceColour, typeof(string)) as string;

			// Create colour BitmapImage using an absolute Uri (generated from stringUri)
			colourBitmap = new BitmapImage(GetAbsoluteUri(stringUri));
		}
	}

	// create and cache greyscale ImageSource
	_sourceGreyscale = new FormatConvertedBitmap(colourBitmap, PixelFormats.Gray8, null, 0);
  }
  catch (Exception e)
  {
	System.Diagnostics.Debug.Fail("The Image used cannot be greyed out.",
				      "Make sure absolute Uri is used, relative Uri may sometimes resolve incorrectly.\n\nException: " + e.Message);
  }
}

 

Feel free to include it in the project.

thanks

Patrick van der Velde

Coordinator
Jun 21, 2011 at 10:36 AM

Hi Patrick,

Thanks for your suggestion, I added it in the source.

Also added a long overdue support for Source and OpacityMask binding.

regards,

Alex.