System.Drawing.Image from ImageSource in Resources

后端 未结 1 1866
悲&欢浪女
悲&欢浪女 2021-01-26 11:35

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:

相关标签:
1条回答
  • 2021-01-26 12:07

    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.

    0 讨论(0)
提交回复
热议问题