2016-08-20 3 views
0

목표는 많은 동일한 크기의 이미지의 바이트를 저장하고 WriteableBitmap에 그려 고성능 비디오를 만듭니다. 나는 다음 코드를 시도BitmapImage의 바이트 단위로 WriteableBitmap에 픽셀을 쓰는 방법은 무엇입니까?

:

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

오류 : 내가 UserControl을에서 동일한 코드를 배치하면 다음 오류를 제공

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. 
    }