4

I am trying to update an image by setting the source property every second, this works however causes a flicker when updated.

CurrentAlbumArt = new BitmapImage();
CurrentAlbumArt.BeginInit();
CurrentAlbumArt.UriSource = new Uri((currentDevice as AUDIO).AlbumArt);
CurrentAlbumArt.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
CurrentAlbumArt.EndInit();

If I don't set IgnoreImageCache, the image does not update thus no flickering either.

Is there a way around this caveat?

Cheers.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
bl4kh4k
  • 1,440
  • 4
  • 20
  • 34
  • You may first download the image buffer completely, then create a MemoryStream from that buffer and finally create a new BitmapImage and assign its `StreamSource` property. – Clemens Aug 18 '13 at 18:42
  • I've tried doing that using a BmpBitmapEncoder however it causes the same flickering to happen. – bl4kh4k Aug 18 '13 at 18:48
  • Why encoder? You want to decode an image. I'll provide some example code. – Clemens Aug 18 '13 at 18:58

1 Answers1

4

The following code snippet downloads the whole image buffer before setting the Image's Source property to a new BitmapImage. This should eliminate any flicker.

var webClient = new WebClient();
var url = ((currentDevice as AUDIO).AlbumArt;
var bitmap = new BitmapImage();

using (var stream = new MemoryStream(webClient.DownloadData(url)))
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

image.Source = bitmap;

If the download takes some time, it would make sense to run it in a separate thread. You would then have to take care for proper cross-thread access by also calling Freeze on the BitmapImage and assigning Source in the Dispatcher.

var bitmap = new BitmapImage();

using (var stream = new MemoryStream(webClient.DownloadData(url)))
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

bitmap.Freeze();
image.Dispatcher.Invoke((Action)(() => image.Source = bitmap));
Clemens
  • 123,504
  • 12
  • 155
  • 268