2016-08-20 18 views
0

目標は、同じサイズの複数のイメージのバイトを格納し、WriteableBitmapで描画して高性能ビデオを作成することです。私は次のコードを試してみましたWriteableBitmapのピクセルをBitmapImageのバイト数で書き込む方法は?

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(); 
    } 

エラー:私は、ユーザーコントロール内の同じコードを配置する場合、それは次のエラーを与える

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.

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

+0

あなたはWriteableBitmapに符号化された画像バッファ(ここではPNG)を書き込むことはできません。代わりに、生のピクセルデータを書き込む必要があります。ソースビットマップからCopyPixelsでそれらを取得します。 – Clemens

+0

それに加えて、全体のアプローチはあまり意味がないようです。ソースビットマップのすべてのピクセルをターゲットWriteabelBitmapにコピーする理由は、ソースビットマップを単純に*表示*できるのはなぜですか? – Clemens

+0

@Clemens、私はWriteableBitmapを初めて使っていて、どのように動作するのかわかりません。どのようにするか、つまり異なるイメージのバイトを格納し、WriteableBitmapで書き込んで高性能ビデオを作成する方法を知りたいと思います。私は自分のコードに似た実例が必要です。ありがとう、私はCopyPixelsを試してみます。一方、キャッシュされたBitmapImageインスタンスの配列によってビデオが更新されました。 –

答えて

1

あなたはCopyPixelsを使用する必要があります。

MainWindow.xaml

<Grid> 
    <Image x:Name="image"></Image> 
</Grid> 

MainWindow.xaml.cs

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

     int stride = bi.PixelWidth * (bi.Format.BitsPerPixel + 7)/8; 
     byte[] data = new byte[stride * bi.PixelHeight]; 

     bi.CopyPixels(data, stride, 0); 

     WriteableBitmap wb = new WriteableBitmap(
      bi.PixelWidth, 
      bi.PixelHeight, 
      bi.DpiX, bi.DpiY, 
      bi.Format, null); 

     wb.WritePixels(
      new Int32Rect(0, 0, bi.PixelWidth, bi.PixelHeight), 
      data, stride, 0); 

     image.Source = wb; // an Image class instance from XAML. 
    } 
関連する問題