Skip to main content
 首页 » 编程设计

c#之将 XAML 文件转换为 BitmapImage

2024年02月02日32langtianya

我想从 XAML(文本)文件创建一个具有所需分辨率的 BitmapImage。 我该怎么做?

谢谢。

请您参考如下方法:

加载 Xaml 文件:

Stream s = File.OpenRead("yourfile.xaml"); 
Control control = (Control)XamlReader.Load(s); 

并创建 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; 
    } 

确保包含正确的库!这些类位于 System.Windows.Media 中。

希望这对您有所帮助!