4

I want to create a BitmapImage with a desired resolution from an XAML (text) file. how can I do that?

thanks.

Askolein
  • 3,250
  • 3
  • 28
  • 40
anton
  • 133
  • 1
  • 14

1 Answers1

6

To load your Xaml file:

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

And creating the 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.

Hope this helps!

Arcturus
  • 26,677
  • 10
  • 92
  • 107
  • Just made a small edit: renamed the **element** var in the SaveImage method be **control**. – anton Jul 25 '12 at 07:04
  • Few questions: 1. how can I control the resolution of the output bitmap? 2. how do I know which DPI to use? – anton Jul 25 '12 at 08:11
  • 2
    1. return a different value for the DesiredSize method, 2. 96 is pretty default.. up it for a higher DPI – Arcturus Jul 25 '12 at 08:53