簡體   English   中英

資源中來自 ImageSource 的 System.Drawing.Image

[英]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設置為ImageSource屬性,然后簡單地將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM