WPF,经常刷新图片而没有闪烁

问题描述 投票:0回答:2

我正在尝试使用WPF从我的网络摄像头创建“实时取景”,它仅通过HTTP给我JPG快照。每次我更新图像源时,它都会闪烁。有人知道如何解决此问题吗?

XAML:

     <Grid>
        <Image Name="img"/>
    </Grid>

C#:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(1000.0);
            timer.Tick += timer_Tick;
            timer.Start();

        }

        void timer_Tick(object sender, EventArgs e)
        {

            BitmapImage _image = new BitmapImage();
            _image.BeginInit();
            _image.CacheOption = BitmapCacheOption.None;
            _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            _image.CacheOption = BitmapCacheOption.OnLoad;
            _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            _image.UriSource = new Uri(@"http://0.0.0.0/api/camera/snapshot?width=640&height=480", UriKind.RelativeOrAbsolute);
            _image.EndInit();
            img.Source = _image;
        }
    }
c# wpf xaml bitmapimage
2个回答
1
投票

闪烁是因为BitmapImage是异步加载的,即在将其分配给Image的Source属性之后。 Image元素首先变为空,并且仅在下载完成后才会显示图像。

在这种情况下,您可以在Source事件处理程序中设置DownloadCompleted属性:

void timer_Tick(object sender, EventArgs e)
{
    var image = new BitmapImage();
    image.BeginInit();
    image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
    image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
    image.UriSource = new Uri(@"http://0.0.0.0/api/camera/snapshot?width=640&height=480");
    image.EndInit();

    if (image.IsDownloading)
    {
        image.DownloadCompleted += (s, ev) => img.Source = image;
    }
    else
    {
        img.Source = image;
    }
}

0
投票

感谢@all的帮助。从Update BitmapImage every second flickers获得了解决方案

void timer_Tick(object sender, EventArgs e)
    {

        var webClient = new WebClient();            
        var _image = new BitmapImage();
        using (var stream = new MemoryStream(webClient.DownloadData(@"http://0.0.0.0/api/camera/snapshot?width=640&height=480")))
        {
            _image.BeginInit();
            _image.CacheOption = BitmapCacheOption.OnLoad;
            _image.StreamSource = stream;
            _image.EndInit();
        }
        img.Source = _image;
    }
© www.soinside.com 2019 - 2024. All rights reserved.