System.Drawing.Image from ImageSource in Resources

2019-03-03 14:49发布

问题:

My question is very similar to this one: wpf image resources and changing image in wpf control at runtime, but with a slight twist.

Here is my ResourceDictionary.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ImageSource x:Key="DisconnectedIcon">Images/disconnect.png</ImageSource>
<ImageSource x:Key="Synced">Images/tick.png</ImageSource>
<ImageSource x:Key="NotSynced">Images/x.png</ImageSource>

As for the C# code behind, I am able to load the ImageSource from the resources with the following. In which, I am able to see the metadata and the image name, but can't figure out how to get it into a System.Drawings.Image.

var imageSource = (ImageSource)Application.Current.FindResource("Synced");

System.Drawing.Image img = Image.FromFile(???)

The reason I am trying to convert it to a System.Drawing.Image is to send it to a printer.

Thanks!

回答1:

In WPF, every UI element extends the Visual Class which Provides rendering support in WPF. There is also a RenderTargetBitmap Class that has a Render Method that takes a Visual object as an input parameter. So you could set your ImageSource as the Source property of an Image and simply render the Image to a Bitmap image:

Image yourImageObject = new Image();
yourImageObject.Source = yourImageSource;

RenderTargetBitmap renderTargetBitmap = 
    new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
renderTargetBitmap.Render(yourImageObject);

// Save to .png file
PngBitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();    
pngBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));    
using (Stream stream = File.Create(filepath))    
{    
    pngBitmapEncoder.Save(stream);    
}

As this is well documented on the internet, I won't bother to repeat the whole story here. To find out the full story, please see the How to Render Bitmap or to Print a Visual in WPF page from the Dot NET Tricks website, which will also help you with your printing requirement.