How to write pixels in WriteableBitmap by bytes from BitmapImage?
<p>The goal is to store bytes of many same sized images and draw them in WriteableBitmap to create high performance video.</p>

<p>I tried next code:</p>

<pre><code>    public MainWindow()
    {
        InitializeComponent();

        Method();
    }

    private void Method()
    {
        BitmapImage bi = new BitmapImage(new Uri(@"Image.png", UriKind.Relative));
        int pw = bi.PixelWidth;
        int ph = bi.PixelHeight;

        WriteableBitmap wb = new WriteableBitmap(
            pw,
            ph,
            96,
            96,
            PixelFormats.Bgra32,
            null);

        byte[] data;
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bi));
        using (MemoryStream ms = new MemoryStream())
        {
            encoder.Save(ms);
            data = ms.ToArray();
        }

        int stride = 4 * pw;

        wb.Lock();
        wb.WritePixels(new Int32Rect(0, 0, pw, ph), data, 4 * pw, 0);
        wb.Unlock();
    }
</code></pre>

<p>Error:</p>

<blockquote>
  <p>Exception thrown: 'System.Windows.Markup.XamlParseException' in PresentationFramework.dll
  Additional information: 'The invocation of the constructor on type 'WpfApplication2.MainWindow' that matches the specified binding constraints threw an exception.' Line number '6' and line position '9'.
  If there is a handler for this exception, the program may be safely continued.</p>
</blockquote>

<p>If I place the same code in UserControl, it gives next error:</p>

<blockquote>
  <p>An unhandled exception of type 'System.ArgumentException' occurred in PresentationCore.dll
  Additional information: Buffer size is not sufficient.</p>
</blockquote>