[英]Convert an XAML file to a BitmapImage
I want to create a BitmapImage with a desired resolution from an XAML (text) file. 我想从XAML (文本)文件中创建具有所需分辨率的BitmapImage 。 how can I do that? 我怎样才能做到这一点?
thanks. 谢谢。
To load your Xaml file: 要加载Xaml文件:
Stream s = File.OpenRead("yourfile.xaml");
Control control = (Control)XamlReader.Load(s);
And creating the BitmapImage: 并创建BitmapImage:
public static void SaveImage(Control control, string path)
{
using (MemoryStream stream = new MemoryStream())
{
GenerateImage(element, stream);
Image img = Image.FromStream(stream);
img.Save(path);
}
}
public static void GenerateImage(Control control, Stream result)
{
//Set background to white
control.Background = Brushes.White;
Size controlSize = RetrieveDesiredSize(control);
Rect rect = new Rect(0, 0, controlSize.Width, controlSize.Height);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)controlSize.Width, (int)controlSize.Height, IMAGE_DPI, IMAGE_DPI, PixelFormats.Pbgra32);
control.Arrange(rect);
rtb.Render(control);
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
png.Save(result);
}
private static Size RetrieveDesiredSize(Control control)
{
control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
return control.DesiredSize;
}
Make sure to include the right libraries! 确保包括正确的库! The classes are located in System.Windows.Media
. 这些类位于System.Windows.Media
。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.