![](/img/trans.png)
[英]Converting System.Drawing.Image to System.Windows.Media.ImageSource with no result
[英]System.Drawing.Image from ImageSource in Resources
我的问题与这个问题非常相似: wpf image resources and changed image in wpf control at runtime ,但略有不同。
这是我的 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>
至于后面的 C# 代码,我可以使用以下内容从资源中加载 ImageSource。 其中,我能够看到元数据和图像名称,但无法弄清楚如何将其放入 System.Drawings.Image。
var imageSource = (ImageSource)Application.Current.FindResource("Synced");
System.Drawing.Image img = Image.FromFile(???)
我试图将其转换为 System.Drawing.Image 的原因是将其发送到打印机。
谢谢!
在 WPF 中,每个 UI 元素都扩展了在 WPF 中提供渲染支持的Visual
Class 。 还有一个RenderTargetBitmap
类,它具有一个将Visual
对象作为输入参数的Render
方法。 因此,您可以将ImageSource
设置为Image
的Source
属性,然后简单地将Image
渲染为Bitmap
图像:
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);
}
由于这在互联网上有详细记录,我不会在这里重复整个故事。 要了解完整故事,请参阅 Dot NET Tricks 网站上的如何在 WPF 中渲染位图或打印视觉效果页面,这也将帮助您满足打印需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.