C#在WPF GUI上显示新接收的帧

时间:2017-02-09 19:32:37

标签: c# wpf user-interface zeromq

我目前在一个客户端上工作,它从服务器接收帧作为字节数组。这些字节数组将转换为BitmapSource。 但是,当我尝试在WPF GUI上显示到达的帧时似乎没有任何反应。

这是接收bytearray,转换它并在GUI上显示它的方法。

public void runSocketRoutine(){

while (true){

    byte[] content = new byte[8294400];
    Console.WriteLine("Waiting for Messages.");

    using (ZMessage message = subscriber.ReceiveMessage()){
        Console.WriteLine("Message received!");
        string pubID = message[0].ReadString();

            /*receive bytearray from publisher*/
            content = message[1].Read();
            Console.WriteLine("size of content: " + message[1].Length);

            /*create BitmapSource out of the bytearray you receive.*/
            BitmapSource source = BitmapSource.Create(1920, 1080, 72, 72, PixelFormats.Bgra32, BitmapPalettes.Gray256, content, 1920 * 4);
            if (source != null){
                Console.WriteLine("source is created");
            }
            /*display image on screen*/
            videoView.Source = source;
            Console.WriteLine("videoView updated");          

    }
}
}

这是我的xaml内容。

<Window x:Class="FrameByteArrayTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:FrameByteArrayTest"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">

<Grid>
    <Viewbox Stretch="Uniform">
        <Image x:Name="imgView" Stretch="UniformToFill">
        </Image>
    </Viewbox>
</Grid>

我甚至通过创建一个带有给定数据路径的URI-Object传递的BitmapImage来显示GUI上的选择png。如果我不在主方法中这样做,似乎我不能再显示任何图片了。

我会感激每一个提示。 许多问候

1 个答案:

答案 0 :(得分:0)

有些东西告诉我你没有在你的UI线程上做I / O.试试这个:

using (ZMessage message = subscriber.ReceiveMessage()){
    Console.WriteLine("Message received!");
    string pubID = message[0].ReadString();

    /*receive bytearray from publisher*/
    content = message[1].Read();
    Console.WriteLine("size of content: " + message[1].Length);

    /*create BitmapSource out of the bytearray you receive.*/
    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
    {
      BitmapSource source = BitmapSource.Create(1920, 1080, 72, 72, 
        PixelFormats.Bgra32, BitmapPalettes.Gray256, content, 1920 * 4);
      if (source != null){
         Console.WriteLine("source is created");
      }
      /*display image on screen*/
      videoView.Source = source;
      Console.WriteLine("videoView updated");          
    }));
}